I am trying to write the following into an XML document:
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
other code here
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>
</html>
However, if I use the following code, it strips out the ‘x:’.
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
System.Xml.XmlElement htmlNode = document.CreateElement("html");
htmlNode.SetAttribute("xmlns:o", "urn:schemas-microsoft-com:office:office");
htmlNode.SetAttribute("xmlns:x", "urn:schemas-microsoft-com:office:excel");
htmlNode.SetAttribute("xmlns", "http://www.w3.org/TR/REC-html40");
document.AppendChild(htmlNode);
System.Xml.XmlElement headNode = document.CreateElement("head");
htmlNode.AppendChild(headNode);
headNode.AppendChild(
document.CreateElement("xml")).AppendChild(
document.CreateElement("x:ExcelWorkbook"))).AppendChild(
document.CreateElement("x:ExcelWorksheets")).AppendChild(
document.CreateElement("x:ExcelWorksheet")).InnerText="other code here";
How can I stop this from happening?
Use the XmlDocument.CreateElement overload which allows you to specify the required prefix & namespace of the element e.g.
Example
From your comment I think you have went ahead and create every element in the way I have suggested. What I was referring to was how to get your Excel specific elements to have the correct namespace prefix. See my example below to see how to properly associate each of your elements with the correct namespace prefix:
Hope that clears things up for you.