0

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>

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I have updated my code to your suggestion and I am still not getting a response. Is "New SimpleXMLElement" the correct function to load the xml into?
Yes, but you can also say simplexml_load_string($xml_string). I've posted the complete code, which works fine for me.
Yes, it is the problem. Your top-level node is collection, not record, and all nodes are in the http://www.loc.gov/MARC21/slim namespace. Please edit your question to reflect reality!
Thank you so much, you're a lifesaver, I can't believe that a namespace was the cause of all of this. Thanks again!

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.