Tutorial :detecting nodes in xml


for example, we have this xml:

<p>[TAG]      <span>foo 1</span>      <span>foo 2</span>     [/TAG]      <span>bar 1</span>      <span>bar 2</span>  </p>  

how can i detect <span>-tags between words [TAG] and [/TAG] ("foo 1" and "foo 2" in this case)?

UPD. for example i need to change nodeValue of each span between [TAG] and [/TAG]


Assuming that you only have one set of [TAG]..[/TAG] per node (as in, if your document has two sets they're within separate <p> elements or whatever), and that they're always siblings:

You can use preceding-sibling and following-sibling to select only elements which are preceded by a [TAG] text node and followed by a [/TAG] text node:

//span[preceding-sibling::text()[normalize-space(.) = "[TAG]"]][following-sibling::text()[normalize-space(.) = "[/TAG]"]]  

A full PHP example:

$doc = new DOMDocument();  $doc->loadHTMLFile('test.xml');    $xpath = new DOMXPath($doc);    foreach ($xpath->query('//span[preceding-sibling::text()[normalize-space(.) = "[TAG]"]][following-sibling::text()[normalize-space(.) = "[/TAG]"]]') as $el) {   $el->nodeValue = 'Changed!';  }    echo $doc->saveXML();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »