When I was using XPath last night, I encountered a problem. It was done only one night later, and I almost didn't vomit blood. The basic knowledge should be solid !!
Assume that the following XML document is available:
To obtain the title of all the songs, we generally use the following XPath expression:
CopyCode The Code is as follows:/playlist/tracklist/track/Title
However, the matching results will disappoint you very much and you will find that nothing can be obtained. So I got stuck on this issue for several hours, and Google finally gave me the answer.
In the playlist node in the second row, there is an xmlns attribute, which is the namespace of XML. Because of the existence of this attribute, the above XPath will be invalid. What should we do? The answer is inProgramRegister the namespace for our XML.
Use C # to register a namespace for XML and obtain the song title:Copy codeThe 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 );
}
Use PHP to register a namespace for XML and obtain the song title:Copy codeThe 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;
}