检查<m>中是否存在<p1>标记将<p1> <a>1223</a> </p1>添加到其中</m> </p1>

时间:2011-05-31 08:15:54

标签: php xml

我的XML是这样的:

<?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>

检查<p1> tag is not existadd this <p1><a>1223</a></p1>是否{。}}。

   <consonant>
      <L>
        <l1>l1</l1>
      </L>
      <M>
      <m1>m1</m1>
      <p1><a>1223</a></p1>
      </M>
      <N>
        <n1>n1</n1>
      </N>
   </consonant>

我在尝试:

   $xml = simplexml_load_string($myxml); // return object
   $nss = $xml->getDocNamespaces(TRUE);
   $xml->registerXPathNamespace('__empty_ns', $nss[""]);
   $result = $xml->xpath("/__empty_ns:Document/__empty_ns:consonant");//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>
          }
   }

并在其上使用对象操作(condifion,loop,append,。)

任何人都可以告诉我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

<?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();

<强>输出

<?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>