I need to get the parent of a particular node in php. I'm using DOMDocument and XPath. My XML is this:
<ProdCategories>
<ProdCategory>
<Id>138</Id>
<Name>Parent Category</Name>
<SubCategories>
<ProdCategory>
<Id>141</Id>
<Name>Category child</Name>
</ProdCategory>
</SubCategories>
</ProdCategory>
</ProdCategories>
The php code:
$dom = new DOMDocument();
$dom->load("ProdCategories_small.xml");
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//ProdCategory/Id[.="141"]/parent::*')->item(0);
print_r($nodes);
The print is:
DOMElement Object ( [tagName] => ProdCategory [schemaTypeInfo] => [nodeName] => ProdCategory [nodeValue] => 141 Category child [nodeType] => 1 [parentNode] => (object value omitted) [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => (object value omitted)
The [parentNode] is (object value omitted), why? I would get
<Id>138</Id>
<Name>Parent Category</Name>`
//ProdCategory[Id[.="141"]], does that work ?//ProdCategory[Id="141"]//ProdCategory[Id='141']/ancestor::ProdCategory/child::*[name() = 'Id' or name()='Name'].ProdCategoryof your xpath expression, the parent node isSubCategories. You have to use theancestoraxis to reach the outerProdcategory- see my previous comment.