xmldocument在同一节点中添加名称空间前缀

时间:2015-03-25 09:10:38

标签: c# namespaces xmldocument

我希望输出如下:

<Order xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:gml="example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd"
xsi:noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">

我用来获取此代码的代码是:

xmlDocument.DocumentElement.SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
xmlDocument.DocumentElement.SetAttribute("xmlns:gml", "example.com");
xmlDocument.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlDocument.DocumentElement.SetAttribute("xsi:schemaLocation", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");     
xmlDocument.DocumentElement.SetAttribute("xsi:noNamespaceSchemaLocation","http://www. xyz.co.uk/xmlorders3/lig_xml_orders.xsd");

但我得到的输出是这样的:

<Order xmlns:gml="example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd" 
       noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">

请建议我以其他方式获得所需的输出。

2 个答案:

答案 0 :(得分:0)

您应该使用其他版本的SetAttribute方法:

xmlDocument.DocumentElement
    .SetAttribute("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");

答案 1 :(得分:-2)

我找到了出路。它可能不是最好的方式。解决方案是:

string xmlString = xmlDocument.InnerXml.ToString(); xmlString = xmlString.Replace(&#34; schemaLocation&#34;,&#34; xsi:schemaLocation&#34;); xmlString = xmlString.Replace(&#34; noNamespaceSchemaLocation&#34;,&#34; xsi:noNamespaceSchemaLocation&#34;); xmlDocument.LoadXml(的xmlString);

//现在我有了所需的xmlDocument。

相关问题