I'm using .NET's XmlDocument class because I need to edit XML documents dynamically.
I'm trying to create an element that looks like this:
<element xmlns:abc="MyNamespace">
Here's the code I've written so far:
XmlDocument xml = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("abc", "MyNamespace");
XmlNode declarationNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(declarationNode);
// Create a root element with a default namespace.
XmlNode rootNode = xml.CreateElement("root", "rootNamespace");
xml.AppendChild(rootNode);
XmlNode containerNode = xml.CreateElement("container", xml.DocumentElement.NamespaceURI);
rootNode.AppendChild(containerNode);
// Create the element node in question:
XmlNode elementNode = xml.CreateElement("element", xml.DocumentElement.NamespaceURI);
XmlAttribute attr = xml.CreateAttribute("abc", "def", nsmgr.LookupNamespace("abc"));
elementNode.Attributes.Append(attr);
containerNode.AppendChild(elementNode);
Here is my output:
<?xml version="1.0" encoding="UTF-8"?>
<rootNode xmlns="MyNamespace">
<container>
<element abc:def="" xmlns:abc="MyNamespace" />
</container>
</rootNode>
It appears the attribute attr is causing both "abc:def=""" and "xmlns:abc="MyNamespace"" to be set--all I want is for the latter?