GuterProgrammierer
GuterProgrammierer

Reputation: 73

C# XNode add a NameSpace

I have a xNode made by JSON.

C# code:

Class class = new Class();
class.ComboBoxChecked = Class.ComboBoxChecked;
class.RadioButtonChecked = Class.RadioButtonChecked;
string test = JsonConvert.SerializeObject(class);
XNode node = JsonConvert.DeserializeXNode(test, "Root");

XML:

<Root>
  <RadioButtonChecked>1</RadioButtonChecked>
  <ComboBoxChecked>5</ComboBoxChecked>
</Root>

My goal is to add a Namespace to it. How can i achieve this?

Upvotes: 1

Views: 330

Answers (1)

Innat3
Innat3

Reputation: 3576

You can add namespaces at root level this way:

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("example", "http://www.w3.org");

    using (var ms = new MemoryStream())
    {
        using (TextWriter writer = new StreamWriter(ms))
        {
            var xmlSerializer = new XmlSerializer(typeof(MyClass));
            xmlSerializer.Serialize(writer, myClassInstance, ns);
            XNode node = XElement.Parse(Encoding.ASCII.GetString(ms.ToArray()));
        }
    }

If you need namespaces in it's children, you can edit your class using the IXmlSerializable interface, here's an Example

Upvotes: 1

Related Questions