tags:

views:

2591

answers:

4

Hello !

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.

Any ideas/techniques would be greatly appreciated. Thanks!

+7  A: 

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.

FlySwat
Thanks for your answer! The XML has a very different (and more complicated) schema than what I showed in my question. I was trying to simplify it for the question :).
sundeep
I'm failing to understand why this is marked as correct, since as DeepBlue says below, the Name property is read only. Fascinating that it received 11 upvotes...
Matthew Talbert
DownVote because XmlNode.Name is readonly
Luis Filipe
I agree. Have you ever had to work with any XML from Apple? It's all like this and an utter pain to parse...
ZombieSheep
It says "pseudo code" which is code for demo purposes only.
Scoregraphic
@ZombieSheep...that's not XML that's plist...p for property or pain...whatever you like more
Scoregraphic
+5  A: 

the XmlNode.Name property is read only

While this is true, it does not answer the question.
Ed Schwehm
A: 

sundeep: I am trying to do the same as you but i can't find any way. How did you do it?

Thanks

Luis Filipe
A: 

Perhaps the beeter solution would be to iterate through each node, and write the information out to a new document. Obviously, this will depend on how you will be using the data in future, but I'd recommend the same reformatting as FlySwat suggested...

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

I'd also suggest that using the XDocument that was recently added would be the best way to go about creating the new document.

ZombieSheep