I am working on an interface with the amazon product advertising API.
I have XML that includes a section similar to this:
<BrowseNodes>
<BrowseNode>
<Name>Category</Name>
<BrowseNodeId>123456</BrowseNodeId>
<Ancestors>
<BrowseNode>
<Name>Whatever</Name>
<BrowseNodeId>987654</BrowseNodeId>
<BrosweNode>
</Ancestors>
</BroseNode>
<BroseNode>
...
</BrowseNode>
</BrowseNodes>
I’ll have to double check my XML. there might be one more level of <BrowseNode> </BrowseNode> outside of the first <BrowseNode> I posted above.
I need to find the <BrowseNode> <Name> that is inside the Ancestors element where the <Ancestors> element is a sibling of the <Name>Category</Name>
I’m just getting started with xpath, and that’s over my head.
I have been coding it like this:
//$XML fromapi
$parsed=simplexml_load_string($XML);
//narrow it down
$s = '/ItemSearchResponse/Items/Item';
$items = $parsed->xpath($s);
//Get only the top level BrowseNodes for this item.
foreach($items as $item)
{
// this narrows it down close to what I posted above.
$s = 'BrowseNodes/BrowseNode';
$top_browsenode_search=$item->xpath($s);
//there may be a simpler way, but I think it is working for me:
foreach ($top_browsenode_search as $top_browsenode)
{
$temp_array=array();//must be emptied each time.
$s = 'Name';
$temp_array['name']=$top_browsenode->xpath($s);
$s = 'BrowseNodeId';
$temp_array['id']=$top_browsenode->xpath($s);
$browsenodes[]=$temp_array;
}
$top_browsenodes[]=$browsenodes;
unset ($browsenodes);
}
Is anyone able to help with that xpath syntax? If not directly, could you point me to any novice friendly documentation you know of? I downloaded a great book on the subject, I’ve learned a lot from it, but It’s a little over my head.
below is not part of the question, but rather evidence that one of the answers was correct. See the comments for details.
Expected result: “Whatever” Given Result: “Whatever”
<?xml version="1.0" ?>
<root>
<BrowseNodes>
<BrowseNode>
<Name>Category</Name>
<BrowseNodeId>123456</BrowseNodeId>
<Ancestors>
<BrowseNode>
<Name>Whatever</Name>
<BrowseNodeId>987654</BrowseNodeId>
</BrowseNode>
</Ancestors>
</BrowseNode>
<BrowseNode>
<Name>SomethingElse</Name>
<BrowseNodeId>951753</BrowseNodeId>
</BrowseNode>
</BrowseNodes>
</root>
BrowseNodes/BrowseNode/Name
Array
(
[0] => SimpleXMLElement Object
(
[0] => Category
)
[1] => SimpleXMLElement Object
(
[0] => SomethingElse
)
)
BrowseNodes/BrowseNode[Name="Category"]/Ancestors/BrowseNode/Name
Array
(
[0] => SimpleXMLElement Object
(
[0] => Whatever
)
)
Thanks!
If you want to get just the node:
If you want to get the node’s text:
In both examples, replace _ with the name for which you are searching.