And last night in the use of XPATH, encountered a problem, changed a night to finish, 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 songs, typically using the following XPATH expressions:
Copy Code code as follows:
/playlist/tracklist/track/title
But the results will be very disappointing and you will find nothing. So I got stuck on this issue for hours, and finally the Almighty Google told me the answer.
In the second line playlist that node, there is an XMLNS attribute, this is the XML namespace (Namespace), and that is because of the existence of this attribute, the XPATH above us is invalid. What to do? The answer is to register the namespace for our XML in the program.
Use C # to register namespaces with XML and get song titles:
Copy Code code 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);
}
Use PHP to register namespaces with XML and get song titles:
Copy Code code 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;
}