2

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.

1
  • All you have to do is set the attribute. Commented Apr 23, 2013 at 6:33

2 Answers 2

3

All you have to do is set the attribute:

one.SetAttributeValue("name", "ID");
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you that works! I have one more question tho. What should I do if I want to change the name of attribute as well? for example, 'EmpID' to 'EmployeeID'. Thank you in advance!
EmpID is not an attribute, but the element name. You can use the Name propery to change that: msdn.microsoft.com/en-us/library/…
0

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

2 Comments

This wouldn't work if the element has attributes, e.g. <OldName foo="bar">
Better use the Name property: msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.