【问题标题】:Symfony DomCrawler with XML and XPath带有 XML 和 XPath 的 Symfony DomCrawler
【发布时间】:2017-01-11 17:38:57
【问题描述】:

我正在尝试获取所有 title 元素并将它们保存在一个数组中。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<mylist>
    <element>
        <id>1</id>
        <title>Example 1</title>
        <status>2</status>
        <my_status>2</my_status>
    </element>
    <element>
        <id>2</id>
        <title>Example 2</title>
        <status>1</status>
        <my_status>1</my_status>
    </element>
    <element>
        <id>3</id>
        <title>Example 3</title>
        <status>2</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>4</id>
        <title>Example 4</title>
        <status>3</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>5</id>
        <title>Example 5</title>
        <status>1</status>
        <my_status>6</my_status>
    </element>
</mylist>

PHP:

$crawler = new Crawler();
$crawler->addXmlContent($data);

$result = $crawler->filterXPath('/mylist/element[not(status=3) and my_status=6]/title/text()');

元素节点需要满足一些条件,所以调用$result-&gt;count()应该打印2(示例3和示例5),但它打印0。

谢谢。

编辑:

找到解决方案,XPath 应该是:

$result = $crawler->filterXPath('//mylist/element[not(status=3) and my_status=6]/title/text()');

【问题讨论】:

  • 如果这解决了您的问题,那么您就有了不同的 XML 结构。

标签: php xml symfony xpath domcrawler


【解决方案1】:

来自 filteXpath 注释

 * The XPath expression is evaluated in the context of the crawler, which
 * is considered as a fake parent of the elements inside it.
 * This means that a child selector "div" or "./div" will match only
 * the div elements of the current crawler, not their children.

然后在修改路径的地方应用内部方法$xpath = $this-&gt;relativize($xpath);

对我来说,最简单的解决方案就是使用像 ./mylist 这样的相对路径。

但是如果你能理解这里发生了什么https://github.com/symfony/dom-crawler/blob/master/Crawler.php#L958绝对路径应该是可能的,我认为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多