Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to create an XML in c#. here is my expected xml result:-

<?xml version="1.0" encoding="utf-8" ?>
<soapenv:Envelope xmlns:soapenv="" xmlns:tem="" xmlns:arr="">

I am facing issue while adding multiple attribute in soapenv:Envelope node. can any one suggest me the solution

What I have tried:

i tried following code but i did not get expected result.
var doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
 var root = doc.AppendChild(doc.CreateElement("SOAP-ENV", "Envelope", soapNs));
var body = root.AppendChild(doc.CreateElement("SOAP-ENV", "Body", soapNs));

 AddAttribute(doc.DocumentElement, "xmlns:soapenv", "");
 AddAttribute(doc.DocumentElement, "xmlns:tem", "");
 AddAttribute(doc.DocumentElement, "xmlns:arr", "");

  private static void AddAttribute(XmlNode node, string attribute, string value)
            if (node.NodeType == XmlNodeType.Element)
                node.Attributes[attribute].Value = value;
                foreach (XmlNode subnode in node.ChildNodes)
                    AddAttribute(subnode, attribute, value);
Updated 3-Nov-22 3:11am

1 solution

Managing Namespaces in an XML Document | Microsoft Learn[^]

Once you add the namespaces to a NameTable, and correct your prefixes, the XmlDocument will add the xmlns attributes for you. NB: It will only add the namespaces that are actually used - in this case, you've only used the Soap namespace, so the tempuri and namespaces will be omitted.
var nt = new NameTable();
var nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("soapenv", soapNs);
nsmgr.AddNamespace("tem", "");
nsmgr.AddNamespace("arr", "");

var doc = new XmlDocument(nt);
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
var root = doc.AppendChild(doc.CreateElement("soapenv", "Envelope", SoapNamespace));
var body = root.AppendChild(doc.CreateElement("soapenv", "Body", SoapNamespace));

If you can switch to XLinq[^], managing namespaces becomes much easier:
XNamespace SoapNs = "";
XNamespace TempNs = "";
XNamespace ArrayNs = "";

var doc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(SoapNs + "Envelope",
        new XAttribute(XNamespace.Xmlns + "soapenv", SoapNs),
        new XAttribute(XNamespace.Xmlns + "tem", TempNs),
        new XAttribute(XNamespace.Xmlns + "arr", ArrayNs),
        new XElement(SoapNs + "Body")
Share this answer
TCS54321 4-Nov-22 1:45am    
thank you. i tried the XLINQ solution. and it work for me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900