Adding a namespace to existing XDocument

泄露秘密 提交于 2019-12-10 13:26:23

问题


I need to manipulate some xml files using Linq to xml.

I have an existing XDocument that I Load

Now I cannot seem to be able to add a namespace to it.

I do:

//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?

How do I Remove/Replace?

many thanks


回答1:


First of all, while XML markup allows you to use

<root xmlns="http://example.com/ns">
  <foo>
    <bar>baz</bar>
  </foo>
</root>

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;
}

If you also want to set a certain prefix pf then addionally set

  xdoc.Root.Add(new XAttribute(XNamespace.Xmlns + "pf", myNs));



回答2:


To add dynamically from one xdocument to another one see http://www.hanselman.com/blog/GetNamespacesFromAnXMLDocumentWithXPathDocumentAndLINQToXML.aspx



来源:https://stackoverflow.com/questions/14294497/adding-a-namespace-to-existing-xdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!