从“SimpleXMLElement对象”中删除节点


remove node from `SimpleXMLElement Object`

XMl

<text font-family="Helvetica" font-size="25" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" >
    <tspan x="-100" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">t</tspan>
    <tspan x="-93" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">e</tspan>
    <tspan x="-79" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">s</tspan>
    <tspan x="-66" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">t</tspan>
</text>

我想做的是,保持第一个tspan和附加所有其他tspan值在第一个tspan和删除所有其他。

他是期望的输出,

<text font-family="Helvetica" font-size="25" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" >
    <tspan x="-100" y="7.87" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: ; opacity: 1;">test</tspan>
</text>

对于我所做的,

$previousValue = null;
$first = $text->tspan[0];
foreach($text->tspan as $k2=>$span){
                if(is_object($span)){
                    $style = $span->attributes()->style;
                    if($previousValue) {
                        if(strcmp($style,$previousValue) === 0){
                            $first.=$span;
                            //$dom=dom_import_simplexml($span); $dom->parentNode->removeChild($dom);
                        }
                    }
                    $previousValue = $style;
                }
            }
            $text->tspan[0] = $first;

这将生成完美的第一个节点,但不会正确删除其他节点。我试过了,

$dom=dom_import_simplexml($span); $dom->parentNode->removeChild($dom);

但它只是删除一个节点,然后打破循环。不知道那里发生了什么。我做错什么了吗?

使用SimpleXMLElement和XPath可以这样做:

$xml = new SimpleXMLElement($xmlString);
$texts = $xml->xpath('//text/tspan/..');
foreach ($texts as $text) {
    $tspans = $text->xpath('//tspan');;
    $currentTspan = array_shift($tspans);

    foreach ($tspans as $tspan) {
        if ($currentTspan['style']->asXML() != $tspan['style']->asXML()) {
            $currentTspan = $tspan;
            continue;
        }
        $currentTspan[0] .= $tspan[0];
        unset($tspan[0]);
    }
}

下面是工作演示。

为了简单起见,我在这里使用了array_shift()函数。它所做的只是返回数组的第一个元素并删除它。