[英]Make XML in c# with namespaces
我需要按以下形式生成 XML:
<ns1:root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
<ns2:item ns2:param="value" />
</ns1:root>
我使用這段代碼:
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("ns2:item"));
xElement.SetAttribute("ns2:param", "value");
但結果如下:
<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2">
<item param="value" />
</root>
謝謝你的建議。
XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("ns2:item" , "http://example.com/xmlns2"));
給我:
<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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.