Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a namespace to existing XDocument

Tags:

linq-to-xml

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

like image 962
user9969 Avatar asked Jan 12 '13 14:01

user9969


People also ask

How do I add a namespace to an XML file?

XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

How do you add a namespace to an XML element in Java?

Add name space to document root element as attribute. Transform the document to XML string. The purpose of this step is to make the child element in the XML string inherit parent element namespace. Now the xml string have name space.

What is namespaces in Xlm document?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.

How do I use XmlNamespaceManager?

To add namespaces to the namespace manager, you create a XmlNamespaceManager object and then use the AddNamespace method. Default prefix and namespace pairs are automatically added to the namespace manager on creation.


1 Answers

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));
like image 150
Martin Honnen Avatar answered Sep 19 '22 08:09

Martin Honnen