I have an XML document with a default namespace attached to it, e.g.
<foo xmlns="http://www.example.com/ns/1.0"> ... </foo>
This is actually a complex XML document that conforms to a complex schema. My task is to parse some data. To help me, I have an XPath table. XPath is pretty deeply nested for example
level1/level2/level3[@foo="bar"]/level4[@foo="bar"]/level5/level6[2]
The person who generates XPath is an expert in the circuit, so I assume that I cannot simplify it or use shortcuts to traverse the object.
I use SimpleXML to parse everything. My problem is how the default namespace is handled.
Since there is a default namespace in the root element, I cannot just do
$xml = simplexml_load_file($somepath); $node = $xml->xpath('level1/level2/level3[@foo="bar"]/level4[@foo="bar"]/level5/level6[2]');
I need to register a namespace , assign it a prefix, and then use the prefix in my XPath, for example
$xml = simplexml_load_file($somepath); $xml->registerXPathNamespace('myns', 'http://www.example.com/ns/1.0'); $node = $xml->xpath('myns:level1/myns:level2/myns:level3[@foo="bar"]/myns:level4[@foo="bar"]/myns:level5/myns:level6[2]');
Adding prefixes is not manageable in the long run.
Is there a proper way to handle default namespaces without using prefixes with XPath?
Using an empty prefix does not work ( $xml->registerXPathNamespace('', 'http://www.example.com/ns/1.0'); ). I can cross out the default namespace for example
$xml = file_get_contents($somepath); $xml = str_replace('xmlns="http://www.example.com/ns/1.0"', '', $xml); $xml = simplexml_load_string($xml);
but this circumvents the problem.
xml php namespaces xpath simplexml
mpdonadio
source share