向现有XDocument添加名称空间 [英] Adding a namespace to existing XDocument
问题描述
我需要使用Linq to xml处理一些xml文件.
I need to manipulate some xml files using Linq to xml.
我有一个已加载的现有XDocument
I have an existing XDocument that I Load
现在我似乎无法为其添加名称空间.
Now I cannot seem to be able to add a namespace to it.
我这样做:
//Load an existing xml into a XDocument
XDocument xdoc=XDocument.Load(myXml);
//Create a namespace
XNamespace myNS="http://www.w3.org/2001/XMLSchema-instance/MyShinyNewNamespace";
xAttribute myAttr=new XAttribute(XNamespace.Xmlns +"myNS",myNS);
//Add new namepsace to root
xdoc.Root ????
What do you do here?
如何检索我的名称空间?
How do I retrieve my namespace?
如何删除/替换?
非常感谢
推荐答案
首先,虽然XML标记允许您使用
First of all, while XML markup allows you to use
<root xmlns="http://example.com/ns">
<foo>
<bar>baz</bar>
</foo>
</root>
使用单个名称空间声明属性将根元素和那些后代元素放入声明的名称空间中,当您操纵树模型时,需要更改所有元素的Name
,因此需要例如
to use a single namespace declaration attribute to put the root element as well as those descendant elements into the declared namespace, when you manipulate the tree model you need to change the Name
of all elements so you need e.g.
XNamespace myNs = "http://example.com/ns";
foreach (XElement el in xdoc.Descendants())
{
el.Name = myNs + el.Name.LocalName;
}
如果您还想设置一个特定的前缀pf
,请另外设置
If you also want to set a certain prefix pf
then addionally set
xdoc.Root.Add(new XAttribute(XNamespace.Xmlns + "pf", myNs));
这篇关于向现有XDocument添加名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!