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

sgm*_*ore 1 c# xml xml-namespaces

我有一个 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>
       ...
Run Code Online (Sandbox Code Playgroud)

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

<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>        
 ...
Run Code Online (Sandbox Code Playgroud)

我尝试过添加

   doc.DocumentElement.SetAttribute("xmlns:p", "http://example.com/schema2");
Run Code Online (Sandbox Code Playgroud)

但是,虽然这将命名空间添加到标头中,但文件的主体并未更改。

har*_*r07 5

您可以简单地更改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");
Run Code Online (Sandbox Code Playgroud)