Home >Backend Development >PHP Tutorial >请问使用DOMXpart如何快速定位某一个DOMElement呢?

请问使用DOMXpart如何快速定位某一个DOMElement呢?

WBOY
WBOYOriginal
2016-06-06 20:49:221194browse

假设有这么一个xml,这个可以不固定

<code><root>
    <home>
        <sea id="s1">
            <uv name="l1">test.1
            <op name="l1">test.2</op>
        </uv></sea>
        <sea id="s2">
            <uv name="l2">test.3</uv>
            <op name="l1">test.4
            <uv name="l1">test.5</uv>
        </op></sea>
    </home>
    <home>...</home>
</root>
</code>

我先通过DOMDocument获取到一个ID截点,如下:

<code>$dom = new DOMDocument;
$s1 = $dom->getElementByID('s1');
// 返回一个DOMElement对象..做一些列操作,略

$xpath = new \DOMXpath;
// 获取ID截点下uv的name属性为l1的截点
</code>

请问,我如何根据DOMElement对象,快速定位到这个截点,而不是从根目录一级一级往下获取,如:

<code>(new DOMXpath)->query('/root/home/sea/uv[name=l1]');
</code>

回复内容:

假设有这么一个xml,这个可以不固定

<code><root>
    <home>
        <sea id="s1">
            <uv name="l1">test.1
            <op name="l1">test.2</op>
        </uv></sea>
        <sea id="s2">
            <uv name="l2">test.3</uv>
            <op name="l1">test.4
            <uv name="l1">test.5</uv>
        </op></sea>
    </home>
    <home>...</home>
</root>
</code>

我先通过DOMDocument获取到一个ID截点,如下:

<code>$dom = new DOMDocument;
$s1 = $dom->getElementByID('s1');
// 返回一个DOMElement对象..做一些列操作,略

$xpath = new \DOMXpath;
// 获取ID截点下uv的name属性为l1的截点
</code>

请问,我如何根据DOMElement对象,快速定位到这个截点,而不是从根目录一级一级往下获取,如:

<code>(new DOMXpath)->query('/root/home/sea/uv[name=l1]');
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn