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
schemas.microsoft.com
namespaces will be omitted.
var nt = new NameTable();
var nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("soapenv", soapNs);
nsmgr.AddNamespace("tem", "http://tempuri.org/");
nsmgr.AddNamespace("arr", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
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 = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace TempNs = "http://tempuri.org/";
XNamespace ArrayNs = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
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")
)
);