1

我无法更改空标签后的文本。怎么解决?,

$xml = '<?xml version="1.0" encoding="utf-8"?>
<book>
    <titlePart>
        <text>hi</text>
        <text>hello</text>
    </titlePart>
    <titlePart>
        <entryReference>hello refence <sref ref="BH002"/>, go go<sref ref="BH003"/> car</entryReference>
        <text>bank</text>
    </titlePart>
</book>';

如何使用 domdocument 修复我的代码以更改空标记后的文本。

最后结果!

<book>
    <titlePart>
        <text>teste 01</text>
        <text>teste 02</text>
    </titlePart>
    <titlePart>
        <entryReference>teste 03 <sref ref="BH002"/>texte 04 <sref ref="BH002"/>texte 05</entryReference>
        <text>teste 06</text>
    </titlePart>
</book>

我的代码!

$xml = '<?xml version="1.0" encoding="utf-8"?>
<book>
    <titlePart>
        <text>hi</text>
        <text>hello</text>
    </titlePart>
    <titlePart>
        <entryReference>hello refence <sref ref="BH002"/>, go go<sref ref="BH003"/> car</entryReference>
        <text>bank</text>
    </titlePart>
</book>';

$array = array("teste 01", "teste 02", "teste 03", "teste 04", "teste 05", "teste 06");

$dom = new DOMDocument();
$dom->loadXml($xml);
$dom->preserveWhiteSpace = true;

$xpath = new DOMXPath($dom);
$result2 = $xpath->query('//book//titlePart//*|//entryReference[sref]//node()//*');

for ($i = $result2->length - 1; $i >= 0; $i --) {
    $nodePre = $result2->item($i); 

    if($result2->item($i)->getAttribute('ref')!="") {
        $tag = $result2->item($i)->getAttribute('ref');
        $varTexto = $array[$i];

    }else{
        $tag = $result2->item($i)->tagName;
        $varTexto = $array[$i];
    }

    $nodeDiv = $dom->createElement($tag, $varTexto); 
    $varNode = $nodePre->parentNode->replaceChild($nodeDiv, $nodePre);


}

       header("Content-type: text/xml");
       echo $dom->saveXML();
4

0 回答 0