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?
You need to actually qualify the element into the correct namespace:
Note, however, that it may be easier to do all of this with the
XDocument
API.