Xmlns problems encountered in operating XML documents and solutions (C # and PHP)

Source: Internet
Author: User
Tags xspf

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.