How to force prefix in all XmlElements in XmlDocument?

670 views Asked by At

I need to create XML like below. Because of retardation of target system. I need to have prefixes in front of all nodes. All nodes need to have "ns0" prefix present.

<?xml version="1.0" encoding="utf-8"?>
<ns0:RootElement xmlns:ns0="http://top-secret">
    <ns0:MainMessage>
        <ns0:Date>1</ns0:Date>
        <ns0:Field1>2</ns0:Field1>
        <ns0:Field2>3</ns0:Field2>
    </ns0:MainMessage>
</ns0:RootElement>

There is no schema. I need to add nodes depending on user input. This is sample of the code that add nodes to "ns0:MainMessage" element:

XmlDocument xml = new XmlDocument();
xml.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><ns0:RootElement xmlns:ns0=\"http://top-secret\"><ns0:MainMessage></ns0:MainMessage></ns0:RootElement>");
XmlElement mainMessageElement = xml.DocumentElement["ns0:MainMessage"];
XmlElement newElement = mainMessageElement.OwnerDocument.CreateElement("Date");
newElement.Prefix = "ns0";
newElement.InnerText = "thisIsTest;
mainMessageElement.AppendChild(newElement);

This produces output like this:

<?xml version="1.0" encoding="utf-8"?>
<ns0:RootElement xmlns:ns0="http://top-secret">
    <ns0:MainMessage>
        <Date>thisIsTest</Date>
    </ns0:MainMessage>
</ns0:RootElement>

While I need output where "Date" element is prefixed with "ns0" like "ns0:Date". Like so:

<?xml version="1.0" encoding="utf-8"?>
<ns0:RootElement xmlns:ns0="http://top-secret">
    <ns0:MainMessage>
        <ns0:Date>thisIsTest</ns0:Date>
    </ns0:MainMessage>
</ns0:RootElement>

How to force this Date element to have ns0 prefix?

1

There are 1 answers

0
Marc Gravell On BEST ANSWER

You need to actually qualify the element into the correct namespace:

var newElement = mainMessageElement.OwnerDocument.CreateElement(
    "Date", "http://top-secret");
newElement.Prefix = "ns0";

Note, however, that it may be easier to do all of this with the XDocument API.