views:

105

answers:

1

Hello - have been stuck on this for days now- How can I loop every node in an XML document and change the text value of the node.

For example go from this:

<root>
    <node1>some text</node1>
    <node2>
        <node3>some more text</node3>
    </node2>
</root>

to something like:

<root>
  <node1>updated text</node1>
  <node2>
    <node3>updated text</node3>
   </node2>
</root>

The code I have that doesn't work is:

NSArray *nodes = [xmlDoc nodesForXPath:@"//*"];

for (NSXMLElement *node in nodes) {
    //In time a function call will go here to change the text:
    NSString *newVal = @"updated text";
    [node setStringValue:newVal];
}

Although it seems to loop ok when i check the contents of XMLDoc it then has this in it:

<root>
  updated text
</root>

Please help if you can I have tried repeated google searches and am pulling my (already thinning) hair out - surely this should be fairly simple?!

Matt.

A: 

It's your xpath expression. //* selects all nodes in the document including the root node. So at some point in the iteration you are setting the string value of the root node which is apparently wiping out all its previous child nodes.

I'm not an expert in xpath, but something like:

/root//*

might do the trick except that node3 will get wiped out for the same reasons. If you look through The XPath tutorial there should be a way in there of selecting all text nodes.

JeremyP
Thanks Jeremy - I'll give it a go and post results.
ar77