check if <p1> tag is not exist in <M> add this <p1><a>1223</a></p1> into it
My XML something like this:
<?xml version="1.0"?>
<document>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
</document>
check if <p1> tag is not exist
in add this <p1><a>1223</a></p1>
into it.
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
<p1><a>1223</a></p1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
I am trying :
$xml = simplexml_load_string($myxml); // return object
$nss = $xml->getDocNamespaces(TRUE);
$xml->registerXPathNamespace('__empty_ns', $nss[""]);
$result = $xml->xpath("/__empty_ns:Document/__empty_ns:consonan开发者_如何学Ct");//consonant node
foreach($result as $key=>$value){ // loop through all <consonant>
if(!array_key_exist('p1')){ // if not exist
$value['p1'] = // add node here <p1><a>1223</a></p1>
}
}
and used the object operation on it (condifion ,loop,append,.)
anybody could tell me how Can I do this ?
You could try something like this:
<?php
$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?>
<document
xmlns:xsd="w3.org/2001/XMLSchema"
xmlns:xsi="w3.org/2001/XMLSchema-instance"
xmlns="urn:iso:std:iso:20022:tech:xsd:test.001.001.02"
>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
<p1>unchanged</p1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
</document>');
$xpath = new DOMXPath($dom);
$xpath->registerNameSpace('what-ever', 'urn:iso:std:iso:20022:tech:xsd:test.001.001.02'); // 'what-ever' can be anything other than an empty string
foreach ($xpath->query('//what-ever:consonant/what-ever:M[not(what-ever:p1)]') as $node) { // select M-nodes without p1-nodes as children
$p1Node = $node->appendChild($dom->createElement('p1'));
// do stuff with $p1Node
$aNode = $p1Node->appendChild($dom->createElement('a', '1234'));
}
header('Content-Type: text/xml; charset="utf-8"');
echo $dom->saveXML();
Output:
<?xml version="1.0"?>
<document>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
<p1><a>1234</a></p1></M>
<N>
<n1>n1</n1>
</N>
</consonant>
<consonant>
<L>
<l1>l1</l1>
</L>
<M>
<m1>m1</m1>
<p1>unchanged</p1>
</M>
<N>
<n1>n1</n1>
</N>
</consonant>
</document>
精彩评论