简体   繁体   中英

How to select grandchild - child in xml using php

I have a xml file and i need to select grandchild or grandchild's child using xpath.

Here is xml file link - XML file I do that with this code:

<?php
        $dom = new DOMDocument();
        $dom->validateOnParse = TRUE;
        $dom->load('file.xml')

        $xpath = new DomXPath($dom);

        $nodes = $xpath->query('//question[@id = "1"]/answer[@id = "1"]/subquestion[@id = "1-1"]/answer[@id = "1-1"]');
?>

Above code work fine but i need shorten query as i don't know the dept of subquestions.

Thanks

You can use the // at any point in the query, so

//question[@id = "1"]//subquestion[@id = "1-1"]/answer[@id = "1-1"]

can find it at any level below the one your after.

You can always play with these things in something like https://www.freeformatter.com/xpath-tester.html which allows you to test your expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM