重写 XMLDocument 以使用命名空间前缀 [英] Rewrite XMLDocument to use namespace prefix

查看:36
本文介绍了重写 XMLDocument 以使用命名空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a XMLDocument which, when I save to file, repeats a namespace on most of the elements, as in

<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>
       ...

是否可以修改此文件,使其在整个文档中使用命名空间前缀,例如

Is it possible to amend this file so that it uses a namespace prefix throughout the document, ie something like

<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");

虽然这将命名空间添加到标题中,但文件的主体没有改变.

but whilst this adds the namespace to the header, the main body of the file is unchanged.

推荐答案

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

You can simply change XmlElement.Prefix property value :

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");

这篇关于重写 XMLDocument 以使用命名空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆