1

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?

  • I just googled, how to add namespace to xml, got this.... [how-to-create-a-document-with-namespaces-linq-to-xml](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-create-a-document-with-namespaces-linq-to-xml) – Jawad Feb 13 '20 at 14:08
  • where you want to add namespace? at root level or node level? – Krishna Varma Feb 13 '20 at 14:09
  • I wan't my namespace on the at the root level, so that I can find it later in my CustomXMLParts of a word Document – GuterProgrammierer Feb 13 '20 at 15:19

1 Answers1

1

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

Innat3
  • 3,561
  • 2
  • 11
  • 29
  • If i read this right, you expect, that I am saving my XML as a normal XML file somewhere, but i dont'. I just create a XNode and then I add it to the CustomXMLParts of a word document. – GuterProgrammierer Feb 13 '20 at 15:17