开发者

How do I loop nodes using NSXML on the Mac and change each node's text value

开发者 https://www.devze.com 2022-12-31 07:00 出处:网络
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.

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'开发者_Go百科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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消