Original: xmlns problems encountered in manipulating XML documents and workarounds (C # and PHP)
Whether it is in PHP or C #, in the operation of XML, we in addition to a node a node to fetch value, there is a very convenient expression, XPath and last night in the use of XPath, encountered a problem, changed a night to fix, almost did not vomit blood. Sure enough basic knowledge to Master solid AH!!
Suppose you have one of the following XML documents:
We want to get the title of all the songs, typically using the following XPATH expression:
The code is as follows:/playlist/tracklist/track/title
But the results of the match will disappoint you and you will find nothing. So I stuck on this issue for hours, and eventually almighty Google told me the answer.
In the second row playlist that node, there is an XMLNS attribute, this is the XML namespace (Namespace), because this property exists, so our XPATH above is invalid. What to do? The answer is to register a namespace for our XML in the program.
Use C # to register namespaces for XML and get song titles:
The code is as follows: XmlDocument XML = new XmlDocument (); Xml. Load ("Music.xml"); XmlNamespaceManager xnm = new XmlNamespaceManager (XML. NameTable); Xnm. AddNamespace ("x", "http://xspf.org/ns/0/"); String XPath = "/x:playlist/x:tracklist/x:track/x:title"; foreach (XmlNode xn in XML. SelectNodes (XPath, xnm)) {Console.WriteLine (xn. InnerText); }
The code is as follows:
$xml = simplexml_load_file (' Music.xml '); $xml->registerxpathnamespace (' x ', ' http://xspf.org/ns/0/'); $xpath = '/x:playlist/x:tracklist/x:track '; $result = $xml->xpath ($xpath); foreach ($result as $row) {echo $row->title;}
xmlns problems and workarounds encountered in manipulating XML documents (C # and PHP)