Alex Rivera | Logout

Change the node names in an XML file using C#

Asked 2009-01-24T01:31:14.033
18

I have a huge bunch of XML files with the following structure:

<Stuff1>
  <Content>someContent</name>
  <type>someType</type>
</Stuff1>
<Stuff2>
  <Content>someContent</name>
  <type>someType</type>
</Stuff2>
<Stuff3>
  <Content>someContent</name>
  <type>someType</type>
</Stuff3>
...
...

I need to change the each of the "Content" node names to StuffxContent; basically prepend the parent node name to the content node's name.

I planned to use the XMLDocument class and figure out a way, but thought I would ask if there were any better ways to do this.

Edit
Report

1 Answer

-34

The XML you have provided shows that someone completely misses the point of XML.

Instead of having

<stuff1>
   <content/>
</stuff1>

You should have:/

<stuff id="1">
    <content/>
</stuff>

Now you would be able to traverse the document using Xpath (ie, //stuff[id='1']/content/) The names of nodes should not be used to establish identity, you use attributes for that.

To do what you asked, load the XML into an xml document, and simply iterate through the first level of child nodes renaming them.

PseudoCode:

foreach (XmlNode n in YourDoc.ChildNodes)
{        
    n.ChildNode[0].Name = n.Name + n.ChildNode[0].Name;
}

YourDoc.Save();

However, I'd strongly recommend you actually fix the XML so that it is useful, instead of wreck it further.

answered 2009-01-24T01:47:00.570

Your Answer