XPath: Get parent node from child node Ask Question

XPath: Get parent node from child node Ask Question

I need get the parent node for child node title 50

At the moment I am using only

//*[title="50"]

How could I get its parent? Result should be the store node.


<?xml version="1.0" encoding="utf-8"?>
<d:data xmlns:d="defiant-namespace" d:mi="23">
    <store d:mi="22">
        <book price="12.99" d:price="Number" d:mi="4">
            <title d:constr="String" d:mi="1">Sword of Honour</title>
            <category d:constr="String" d:mi="2">fiction</category>
            <author d:constr="String" d:mi="3">Evelyn Waugh</author>
        </book>
        <book price="8.99" d:price="Number" d:mi="9">
            <title d:constr="String" d:mi="5">Moby Dick</title>
            <category d:constr="String" d:mi="6">fiction</category>
            <author d:constr="String" d:mi="7">Herman Melville</author>
            <isbn d:constr="String" d:mi="8">0-553-21311-3</isbn>
        </book>
        <book price="8.95" d:price="Number" d:mi="13">
            <title d:constr="String" d:mi="10">50</title>
            <category d:constr="String" d:mi="11">reference</category>
            <author d:constr="String" d:mi="12">Nigel Rees</author>
        </book>
        <book price="22.99" d:price="Number" d:mi="18">
            <title d:constr="String" d:mi="14">The Lord of the Rings</title>
            <category d:constr="String" d:mi="15">fiction</category>
            <author d:constr="String" d:mi="16">J. R. R. Tolkien</author>
            <isbn d:constr="String" d:mi="17">0-395-19395-8</isbn>
        </book>
        <bicycle price="19.95" d:price="Number" d:mi="21">
            <brand d:constr="String" d:mi="19">Cannondale</brand>
            <color d:constr="String" d:mi="20">red</color>
        </bicycle>
    </store>
</d:data>

ベストアンサー1

Use the parent axes with the parent node's name.

//*[title="50"]/parent::store

この XPath は、親ノードが である場合にのみそれを選択しますstore

しかし、これらのいずれかを使用することもできます

//*[title="50"]/parent::*
//*[title="50"]/..

これらの xpath は任意の親ノードを選択します。そのため、ドキュメントが変更されると、予期したノードではない場合でも、常にノードが選択されます。

編集

親が自転車で、親の親が店舗である例では何が起こるでしょうか?

上昇しますか?

いいえ、一致するノードの親である場合にのみストアが選択されます//*[title="50"]

そうでない場合、そのような場合に上昇し、そのような親がない場合は None を返す方法はありますか?

はい、ancestor斧を使うことができます

//*[title="50"]/ancestor::store

これにより、一致するノードのすべての祖先が//*[title="50"]`ストアとして選択されます。例:

<data xmlns:d="defiant-namespace" d:mi="23">
    <store mi="1">
        <store mi="22">
            <book price="8.95" d:price="Number" d:mi="13">
                <title d:constr="String" d:mi="10">50</title>
                <category d:constr="String" d:mi="11">reference</category>
                <author d:constr="String" d:mi="12">Nigel Rees</author>
            </book>
        </store>
    </store>
</data>

XPath選択結果

おすすめ記事