Toykeat
Toykeat

Reputation: 127

How to replace tag names in XML file using C#?

I'm new to XML, so this might be an easy question. I have a XML file structured as below.

<root>
 <Test>
   <EmpID>23</EmpID>
   <EmpName>Packman</EmpName>
   <EmpAge>33</EmpAge>
 </Test>
 <Test>
   <EmpID>34</EmpID>
   <EmpName>James</EmpName>
   <EmpAge>13</EmpAge>
 </Test>
 <Test>
   <EmpID>53</EmpID>
   <EmpName>Nedved</EmpName>
   <EmpAge>52</EmpAge>
 </Test>
<root>

I want to replace some of elements in the XML file like below

<root>
 <Test>
   <EmpID name="ID">23</EmpID>
   <EmpName name="Nickname">Packman</EmpName>
   <EmpAge name = "Age">33</EmpAge>
 </Test>
 <Test>
   <EmpID name="ID">34</EmpID>
   <EmpName name="Nickname">James</EmpName>
   <EmpAge name = "Age">13</EmpAge>
 </Test>
 <Test>
   <EmpID name="ID">53</EmpID>
   <EmpName name="Nickname">Nedved</EmpName>
   <EmpAge name = "Age">52</EmpAge>
 </Test>
</root>

So basically I want to relace or add? element to attribute.

ex)

<EmpID>value</EmpID> to <EmpID name="ID">value</EmpID>

I've tried some of references, but they didn't work for me. Below is the one that I tried, but it replaces whole line.

XDocument xdoc1 = XDocument.Load("C:\\Test\\Test.xml");
XElement one = xdoc1.Descendants("EmpID").First();
one.ReplaceWith("EmpID name=NickName");
xdoc1.Save("C:\\Test\\Test_Modified.xml");

The point is center 'value' should not change. See below.

<EmpID>value</EmpID> to <EmpID name="ID">value</EmpID>

Please give me some ideas how to solve this.

Upvotes: 2

Views: 1440

Answers (2)

Santosh Panda
Santosh Panda

Reputation: 7341

To change the attribute you can go with above solution:

one.SetAttributeValue("name", "ID");

And the easiest way I found to rename a node is:

xmlNode.InnerXmL = newNode.InnerXml.Replace("OldName>", "NewName>")

Don't include the opening < to ensure that the closing tag is renamed as well.

You can refer this link also: http://www.goodgord.com/2006/10/how-to-rename-xml-node-in-c.html

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33511

All you have to do is set the attribute:

one.SetAttributeValue("name", "ID");

Upvotes: 3

Related Questions