Search code examples
phpxmlxpathdomxpath

Select a node based on the attributes then return the sibling nodes attribute in php


I am trying to get the content of the field[@value] attribute when the sibling node has field[@value='SIM Identification (ICCID)'. I need to do this with multiple xml docs and the parent node is not always located in the same array position so i need to use relative paths.

here is an example of the xml doc.

     <views>
       <view name="Summary">
         <item>
           <field name="Subject" value="Date Created" class=""/>
           <field name="Data" value="6/24/2013 11:06:54 AM" class=""/>
         </item>
       <view name="Case Data">
         <item>
           <field name="Subject" value="Case Reference" class=""/>
         </item>
       <view name="General Information">
         <item>
           <field name="Attribute" value="Device Name" class=""/>
           <field name="Data" value="SIM Card" class=""/>
         </item>
         <item>
           <field name="Attribute" value="SIM Identification (ICCID)" class=""/>
           <field name="Data" value="8935301120426207248" class=""/>
         </item>
       </view>
     </views>

Here is what I have come up with so far but can't quite get it to work.

    $doc = new DOMDocument;
    $doc->load('../SIMxml/207248.xml');
    $xpath = new DOMXPath($doc);

    $SIM_num_query = "/views/view[@name='General Information']/item [field[@name='Attribute' and @value='SIM Identification (ICCID)' and preceding-sibling::field[@value]]]/";

    echo $xpath->query($SIM_num_query),"<br/>";

This does not work, any suggestions?


Solution

  • If it is always the following field you are looking for try this:

    "//field[@value='SIM Identification (ICCID)']/following-sibling::field/@value"
    

    If it the position is not fix you may try something like this:

    "//field[@value='SIM Identification (ICCID)']/../field[@name='Data']/@value"