tags:

views:

29

answers:

2

I followed the tut in w3school

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 return a empty array. I want select all the <book> element only (not include the <bookstore> and the <?xml version?> header)

in the w3school example, the "//bookstore" can select all the child nodes of the bookstore element

Anybody can tell me why I got a empty array? Thanks

+1  A: 

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
Alejandro
+1  A: 

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.

Dimitre Novatchev
+1 for avoiding `//`
DevNull