1

この XPath クエリを使用して、Xhtml ドキュメントに入力子孫を持たない要素を選択しています。

//*[not(descendant-or-self::input | descendant-or-self::textarea | descendant-or-self::select | ancestor::select)]

次の XHtml ドキュメントの例を使用します。

<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <div id="one">
            <input type="text" />
        </div>
        <div id="two">
            <textarea></textarea>
        </div>
        <div id="three">
            <div id="four">
                Text
            </div>
        </div>
        <div id="five">
            <select>
                <option>One</option>
                <option>Two</option>
            </select>
        </div>
        <div id="six">
            <input type="text" />
        </div>
        <div id="seven">
            <div id="eight"></div>
        </div>
    </body>
</html>

...そしてこのPHPコード:

// Populate $html and $query with above

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadXML($html);

$xpath = new DOMXPath($dom);
$nodes = $xpath->query($query);

foreach($nodes as $node)
{
    echo $node->tagName;

    if($node->hasAttribute('id'))
        echo '#' . $node->getAttribute('id');

    echo ' ';
}

私はこれを得る:head title div#three div#four div#seven div#eight

しかし、代わりにこれが欲しい:head div#three div#seven

XPath クエリの結果を取得し、DOMDocument から要素を削除します。title div#four div#eightは の子でhead div#three div#seven、既に結果に含まれています。

このクエリは任意の XHtml ドキュメントで使用されることに注意してください。目的の結果を得るには、XPath 1.0 クエリをどのように変更すればよいでしょうか?

4

2 に答える 2

1

親の条件を繰り返すだけです:

[not(descendant-or-self::input | descendant-or-self::textarea | descendant-or-self::select | ancestor-or-self::select)
and 
(../descendant-or-self::input | ../descendant-or-self::textarea | ../descendant-or-self::select | ../ancestor-or-self::select)]
于 2012-02-14T10:57:45.073 に答える