Search code examples
c#xmlxml-namespacesxmldocument

Make XML in c# with namespaces


I need to generate XML in the following form:

<ns1:root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
    <ns2:item ns2:param="value" />
</ns1:root>

I use this code:

XmlDocument xDoc = new XmlDocument();
XmlElement xRootElement = (XmlElement)xDoc.AppendChild(xDoc.CreateElement("ns1:root"));
xRootElement.SetAttribute("xmlns:ns1", "http://example.com/xmlns1");
xRootElement.SetAttribute("xmlns:ns2", "http://example.com/xmlns2");
XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("ns2:item"));
xElement.SetAttribute("ns2:param", "value");

But the result is the following:

<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
    <item param="value" />
</root>

Thanks for the advice.


Solution

  • XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("ns2:item", "http://example.com/xmlns2"));

    Gave me:

    <root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
      <ns2:item param="value" />
    </root>
    

    By the way, "ns2:param" is not necessary. XML attributes belong to the same namespace as the element.