goutham
goutham

Reputation: 3

Linq to XML, C#

I have an xml in XDocument object (LINQ to XML). I need to add the namespace to each Xelement/node in the Xdocument.

I dont want to add in the below way. beceause i already have the xml in xdoc.

XDocument xDoc = new XDocument(
new XElement(ns + "root",
new XElement(ns + "person",
new XAttribute("id", 1),
new XElement(ns + "firstname", "jack"),

Below is the format i have

<root>
  <person>1</person>
  <firstname>jack</firstname>
</root>

I want to convert it to this below format

<emp:root>
  <emp:person>1</emp:person>
  <emp:firstname>jack</emp:firstname>
</emp:root>

Upvotes: 0

Views: 146

Answers (1)

msarchet
msarchet

Reputation: 15242

foreach (var node in xDoc.Descendants()) 
{ 
    node.Name = ns + node.Name.LocalName; 
}

That should work:

Side note the namespace will only appear on the root node.

Upvotes: 1

Related Questions