The xmlns problem of manipulating XML documents and Solutions (C # and PHP) _c# tutorials

Source: Internet
Author: User
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;
}

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.