C# 使用名称空间在c中生成XML
我需要以以下形式生成XML:C# 使用名称空间在c中生成XML,c#,xml,xml-namespaces,xmldocument,C#,Xml,Xml Namespaces,Xmldocument,我需要以以下形式生成XML: <ns1:root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2"> <ns2:item ns2:param="value" /> </ns1:root> 但结果如下: <root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.co
<ns1:root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
<ns2:item ns2:param="value" />
</ns1:root>
但结果如下:
<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
<item param="value" />
</root>
感谢您的建议。
<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
<ns2:item param="value" />
</root>
顺便说一下,ns2:param不是必需的。XML属性与元素属于同一名称空间。请尝试以下操作:
XmlDocument xDoc = new XmlDocument();
XmlElement xRootElement = (XmlElement)xDoc.AppendChild(xDoc.CreateElement("ns1:root"));
xRootElement.SetAttribute("xmlns:ns1", "http://example.com/xmlns1");
xRootElement.SetAttribute("xmlns:ns2", "http://example.com/xmlns2");
XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("item", "http://example.com/xmlns1"));
xElement.SetAttribute("param", "http://example.com/xmlns1", "value");
示例是如何创建具有名称空间的XML
XmlDocument xDoc = new XmlDocument();
XmlElement xRootElement = (XmlElement)xDoc.AppendChild(xDoc.CreateElement("ns1:root"));
xRootElement.SetAttribute("xmlns:ns1", "http://example.com/xmlns1");
xRootElement.SetAttribute("xmlns:ns2", "http://example.com/xmlns2");
XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("item", "http://example.com/xmlns1"));
xElement.SetAttribute("param", "http://example.com/xmlns1", "value");