Search code examples
c#xmlxml-namespacesprefix

creating elements with namespace prefix based on multipart xml root declaration


If I do something like this:

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlElement e = xmlDoc.CreateElement("ShipmentReceiptNotification");
e.SetAttribute("xmlns", "urn:rosettanet:specification:interchange:ShipmentReceiptNotification:xsd:schema:02.02");
e.SetAttribute("xmlns:ssdh", "urn:rosettanet:specification:domain:Procurement:AccountClassification:xsd:codelist:01.03");
XmlNode ShipmentReceiptNotification0Node = e;

ShipmentReceiptNotification0Node.InnerText = String.Empty;
xmlDoc.AppendChild(ShipmentReceiptNotification0Node);
XmlNode DocumentHeader1Node = xmlDoc.CreateElement("ssdh:DocumentHeader");
ShipmentReceiptNotification0Node.AppendChild(DocumentHeader1Node);

It will result in the prefix of the second node ssdh not to display, only DocumentHeader is displayed. How could I fix this?


Solution

  • You need to create it like this:

    XmlNode DocumentHeader1Node = xmlDoc.CreateElement("ssdh", "DocumentHeader", "urn:rosettanet:specification:domain:Procurement:AccountClassification:xsd:codelist:01.03");
    

    The point is XmlDocument needs to know which namespace prefix (first argument) corresponds which namespace URI (third argument). A little bit counter-intuitive, but this is the way it works.

    Also note that the line ShipmentReceiptNotification0Node.InnerText = String.Empty; is useless; it's safe to omit it, the element is empty by default.