Timothy Rajan
Timothy Rajan

Reputation: 1957

Adding a namespace to a particular node using C#

I have an XML and a section of the XML looks like below

<ts:mynode1>
   <ts:systemId>XXX</ts:systemId>
   <ts:sequenceId>YYY</ts:sequenceId>
<ts:/mynode1>
<mynode2>
   <systemId>ZZZ</systemId>
   <sequenceId>AAA</sequenceId>
</mynode1>

My objective is to add namespace ts to those nodes which does not have a nodes which does not have a nodespace

is there a way of accomplishing it in C#?

Upvotes: 0

Views: 319

Answers (1)

Sean O&#39;Brien
Sean O&#39;Brien

Reputation: 183

This can be done easily enough using the objects in System.Xml.Linq; in particular, XElement and XName. To give a completely definitive answer I would need to see the rest of your XML (in particular, whatever namespace ts resolves to when it's fully resolved, or the xmlns:ts='http://your/namespace/here' specified earlier in the document.) However, if ts did resolve to the example used above (http://your/namespace/here), you could use the following code to set the ts namespace on every node in the document, assuming "xml" contains the documents XML.

function addNamespaces(string xml){
    var doc = System.Xml.Linq.XDocument.Parse(xml);
    foreach(var el in doc.Descendants())
        el.Name = "{http://your/namespace/here}" + el.Name.LocalName;
    return doc.ToString();
}

Upvotes: 1

Related Questions