mko
mko

Reputation: 22044

Using XPath to select certain nodeName

I followed the tutorial on W3Schools.

http://www.w3schools.com/xpath/xpath_syntax.asp

It says:

nodename Selects all child nodes of the named node

bookstore Selects all the child nodes of the bookstore element

and here's my code

bookstore.xml:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>
      <title lang="eng">Harry Potter</title>
      <price>29.99</price>
    </book>
    <book>
      <title lang="eng">Learning XML</title>
      <price>39.95</price>
    </book>
    </bookstore>

the php file:

    <?php
    $xml = simplexml_load_file("bookstore.xml");
    if(!$xml)
    { 
    echo 'bad';
    }else
    {

    $res = $xml->xpath("//bookstore");

    when I use $res = $xml->xpath("bookstore");
    $xml_res1 = $res1->asXML("booklist.xml");
    }
    ?>

It only returns an empty array. I want to select all of the <book> elements only (not to include the <bookstore> and the <?xml version?> header)

In the W3Schools example, the "//bookstore" can select all the child nodes of the bookstore element.

Can anybody tell me why I got an empty array? Thanks!

Upvotes: 0

Views: 1785

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

Use:

/*/book

or even

/*/*

Of course, you may also use:

/bookstore/book

or even

/child::bookstore/child::book

Given the provided XML document, all the above expressions select exactly the wanted nodes -- all book elements in the document.

Always try to avoid using the // abbreviation as it may result in very inefficient evaluation.

Upvotes: 1

user357812
user357812

Reputation:

That statement should be: Selects all child nodes with this name.

That's why it's called name test in specs 1 2.

If you want book elements:

/bookstore/book

Upvotes: 1

Related Questions