Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用名称空间在c中生成XML_C#_Xml_Xml Namespaces_Xmldocument - Fatal编程技术网

C# 使用名称空间在c中生成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

我需要以以下形式生成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.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");