如何为 Xpath 中的每个父节点在不同数量的子节点值之间添加分隔符


How to add separators between different numbers of children node values, for each parent node in Xpath

如果在 PHP DOMXPath 中可以这样做的任何想法:例如,我有 3 个父跨度,每个跨度中随机数量的子级。首先,我收集这样的数据:"//span[@class='parent']"并得到第一项类似于"Child TextChildText2Child Text 3"的节点值。

但是,我试图用逗号分隔符获得类似" Child Text,ChildText2,Child Text 3 "的东西。

有什么想法吗?我希望能够识别哪些孩子属于哪个父母,同时我正在收集父母内部的其他数据:

<span class="parent">Parent 1
    <span class="child">Child Text</span>
    <span class="child">ChildText2</span>
    <span class="child">Child Text 3</span>
</span>
<span class="parent">Parent 2
    <span class="child">Child Text4</span>
    <span class="child">ChildText5</span>
</span>
<span class="parent">Parent 3
    <span class="child">Child Text6</span>
    <span class="child">Child Text7</span>
    <span class="child">ChildText8</span>
    <span class="child">Child Text 9</span>
</span>

以下PHP是我目前使用的:

$array  = [];
$result = $xpath->query("//span[@class='parent']");
for ($x=0; $x<$result->length; $x++){
    $array[$x]['children'] = trim($result->item($x)->nodeValue);
}

我会直接在PHP中做到这一点,而不是试图对xpath本身太花哨。只需将节点值放入数组中,并用逗号作为分隔符implode()即可。


例:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//span[@class="parent"]') as $parent) {
    $childText = [];
    foreach ($xpath->query('span[@class="child"]', $parent) as $child) {
        $childText[] = trim($child->nodeValue);
    }
    echo implode(',', $childText), "'n";
}

输出:

Child Text,ChildText2,Child Text 3
Child Text4,ChildText5
Child Text6,Child Text7,ChildText8,Child Text 9

使用 xpath> 2:

'string-join(//span[@class="parent"]/span, ",")'

输出:

Child Text,ChildText2,Child Text 3,Child Text4,ChildText5,Child Text6,Child Text7,ChildText8,Child Text 9