0

I am a situation where I'd like to add the same content in several locations in an XML file. FYI - first time tackling DOMDocument. Say the xml looks like

<rrd>
  <rra>
    <cdp_prep>
      <ds>
        <value>nan</value>
      </ds>
      <ds>
        <value>nan</value>
      </ds>
      <ds>
        <value>nan</value>
      <ds>
     </cdp_prep>
     <database>
        ...
     </database>
   </rra>
  <rra>
    <cdp_prep>
      <ds>
        <value>nan</value>
      <ds>
      </ds>
        <value>nan</value>
      <ds>
      <ds>
        <value>nan</value>
      </ds>
     </cdp_prep>
     <database>
        ...
     </database>
   </rra>
</rrd>

If i use something like $rrdCDPds = $xRRD->query("/rrd/rra/cdp_prep/ds"); then i would get all the <ds> elements. In this case i would have a length of 6. However, I'm trying to insertBefore on the second <ds> of each <cdp_prep> element. My issue is if i query on "/rrd/rra/cdp_prep", how do i target the insertBefore on the 2nd <ds> element for every <cdp_prep> element?

2
  • The xml is not valid .. did you mean to close the ds elements? Commented May 4, 2012 at 22:41
  • yes sorry. friday afternoon... and beating head on keyboard :) Commented May 7, 2012 at 12:28

2 Answers 2

1

You can use the child axis in XPath to select the second ds child:

/rrd/rra/cdp_prep/child::ds[2]
Sign up to request clarification or add additional context in comments.

Comments

0

Basic procedure is:

  1. Select the nodes you want to use as insertBefore reference nodes. You can get this using the child axis and a position test: cdp_prep/child::ds[position()=2], which can be abbreviated as cdp_prep/ds[2].
  2. Prepare the nodes you want to insert.
  3. For each matching reference node, clone the node you want to insert and then insert it.

Example:

$dom = new DOMDocument();
$dom->loadXML($xml);
$xp = new DOMXPath($dom);

$newcontent = $dom->createDocumentFragment();
$newcontent->appendChild($dom->createElement('NEWCONTENT'));
$newcontent->appendChild($dom->createTextNode("\n      "));

$DSs = $xp->query('/rrd/rra/cdp_prep/ds[2]');

foreach ($DSs as $ds) {
    $ds->parentNode->insertBefore($newcontent->cloneNode(true), $ds);
}

echo $dom->saveXML();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.