重写XMLDocument以使用名称空间前缀

sgmoore

我有一个XMLDocument,当我将其保存到文件时,它会在大多数元素上重复一个名称空间,例如

<Test>
    <Test xmlns="http://example.com/schema1">

      <Name xmlns="http://example.com/schema2">xyz</Name>
      <AddressInfo xmlns="http://example.com/schema2">
        <Address>address</Address>
        <ZipCode>zzzz</ZipCode>
      </AddressInfo>
       ...

是否可以修改此文件,使其在整个文档中使用名称空间前缀,即类似

<Test xmlns="http://example.com/schema1" xmlns:p="http://example.com/schema2"  >

 <p:Name>xyz</p:Name>
 <p:AddressInfo">
   <p:Address>address</p:Address>
   <p:ZipCode>zzzz</p:ZipCode>
 </p:AddressInfo>        
 ...

我尝试添加

   doc.DocumentElement.SetAttribute("xmlns:p", "http://example.com/schema2");

但是,尽管这会将名称空间添加到标题中,但文件的主体保持不变。

har07

您可以简单地更改XmlElement.Prefix属性值

doc.DocumentElement.SetAttribute("xmlns:p", "http://example.com/schema2");
//xpath for selecting all elements in specific namespace :
var xpath = "//*[namespace-uri()='http://example.com/schema2']";
foreach(XmlElement node in doc.SelectNodes(xpath))
{
    node.Prefix = "p";
}
doc.Save("path_to_file.xml");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章