xmlns problems and workarounds encountered in manipulating XML documents (C # and PHP)

Source: Internet
Author: User
Tags xpath xspf

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)

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.