如何更改名称空间的前缀?

时间:2020-10-10 10:08:32

标签: c# .net xml powershell xml-parsing

如何进行转换

<d xmlns='uri' xmlns:a='uri'>
    <a:c/>
    <c a:atr=':a:b:c:d:e:f:'/>
</d>

进入

<d xmlns='uri' xmlns:b='uri'>
    <b:c/>
    <c b:atr=':a:b:c:d:e:f:'/>
</d>

有可能吗?最好使用System.Xml.XmlDocument

如果.Net无法实现,您知道吗?

1 个答案:

答案 0 :(得分:0)

我对该API有点不满意,但是您应该可以使用XDocument来替换名称空间:

var document = XDocument.Load(@"E:\input.xml");

// Find and remove the namespace
document.Root.Attribute(XNamespace.Xmlns + "a").Remove();

// Add a new namespace with same uri and different prefix
document.Root.Add(new XAttribute(XNamespace.Xmlns + "b", "uri"));

document.Save(@"E:\output.xml");

保存时,XDocument会重新生成XML,并且只要您保持相同的uri,就应该应用新的前缀。