Why does XPath select nodes outside of context node?

后端 未结 2 758
挽巷
挽巷 2021-01-21 00:13

I\'m using XPath with Node.js and I have the following HTML document, where I want to select all article nodes and then in a second step all divs with class \"abc\"

相关标签:
2条回答
  • 2021-01-21 00:56

    Andersson has already provided the correct direct answer to your question (+1), but here is just another option: You can combine your two XPaths into one: This XPath,

    //article[0]/div[@class='abc']
    

    will select the same div element as your two step process does.

    You can even be more elaborate at any step in the path. This XPath will select the div elements with @class='abc' within article elements with a div child whose string value is 123456:

    //article[div='123456']/div[@class='abc']
    

    For the particular XML document shown, the predicate on article selects all articles, but this possibility for refinement exists in general.

    0 讨论(0)
  • 2021-01-21 01:10

    You should note that // means search wherever on the page starting from root element while .// means search wherever on the page starting from the current node. So if you want to start search from already found article element you need to replace

    "//div[@class='abc']"
    

    with

    ".//div[@class='abc']"
    

    or

    "./div[@class='abc']"
    

    as div is the direct child of article

    0 讨论(0)
提交回复
热议问题