简体   繁体   中英

Parsing Complex XML Document using PHP xPath

I have an XML Structure, like I have outline below. I am trying to use xPath to find particular elements within the structure, but have been unsuccessful. This is what I have thus far:

$resultset[0]['bibXML'] - Here is a paste of exactly what is being passed in this variable. http://pastebin.com/CwtFG5dj

Here is a link to the output of the $myNode using print_r(). http://pastebin.com/TwDaxs42

$myNode = new SimpleXMLElement($resultset[0]['bibXML']);
$bnum = $myNode->xpath("record/datafield[@tag='035']/subfield[@code='a']");


<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
<record>
    <leader>01220nam  2200265   4500</leader>
    <controlfield tag="001">ocm00000197</controlfield>
    <datafield tag="035" ind1="" ind2="">
        <subfield code="a">.b10000021</subfield>
        <subfield code="b">a    </subfield>
        <subfield code="c">-</subfield>
    </datafield>
    <datafield tag="245" ind1="" ind2="">
        <subfield code="a">Some Book Title</subfield>
        <subfield code="b">a    </subfield>
        <subfield code="c">-</subfield>
    </datafield>
</record>
</collection>

Your elements are in the http://www.loc.gov/MARC21/slim namespace. Learn about xml namespaces .

Your XPath is matching elements in the null namespace because they are not prefixed. Since your elements are not actually in the null namespace, your XPath does not match anything.

You need to register a namespace prefix with the registerXPathNamespace method and then use that prefix to qualify your element names.

This would be your complete code:

$myNode = simplexml_load_string($resultset[0]['bibXML']);

$myNode->registerXPathNamespace('m21s', 'http://www.loc.gov/MARC21/slim');

$results = $myNode->xpath('m21s:record/m21s:datafield[@tag="035"]/m21s:subfield[@code="a"]');
$bnum = ($results) ? (string) $results[0] : null;

var_export($bnum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM