php xml dom getElementById和DOMXpath查询无法获取元素

Zee*_*ats 3 php xml getelementbyid domdocument domxpath

我在使用函数替换XML文件中的问题和答案元素时遇到了一些问题.我做了很多研究学习php dom,但是我正忙着制作这个功能.问题是当我试图通过属性id获取父元素行时它返回null或当我使用xpath时它返回一个空对象.我得到正确的父元素后,我不知道该函数是否正常工作,但这是我认为的下一步.

我的XML看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row id="1">
    <question>Wat doet de vuilnisman?</question>
    <answer>Hij tilt de vuilnisbak in de vuilnisauto.</answer>
  </row>
  <row id="2">
    <question>Wat zegt de tandarts vaak?</question>
    <answer>U mag nu spoelen.</answer>
  </row>
</root>
Run Code Online (Sandbox Code Playgroud)

和我的PHP功能:

//modifies rows
function modifyRows($file, $rowIds, $rowText) {
    $xmlDoc = new DOMDocument();
    $xmlDoc->preserveWhiteSpace = false;
    $xmlDoc->formatOutput = true;   
    $xmlDoc->load($file);
    foreach($rowIds as $rowId) {
        $parent = $xmlDoc->getElementById($rowId);
        for($i=0;$i<count($rowText);$i++) {
            $newQ = $xmlDoc->createElement('question');
            $qText = $xmlDoc->createTextNode($rowText[$i]);
            $qText = $newQ->appendChild($qText);
            $newA = $xmlDoc->createElement('answer');
            $aText = $xmlDoc->createTextNode($rowText[$i++]);
            $aText = $newA->appendChild($aText);
        }
        $oldQ = $parent->getElementsByTagName('question');
        $oldA = $parent->getElementsByTagName('answer');        
        $parent->replaceChild($newQ, $oldQ);
        $parent->replaceChild($newA, $oldA);
    }   
    $xmlDoc->save($file);
}
Run Code Online (Sandbox Code Playgroud)

$ rowIds是一个数组,其中包含在数组中修改的ans rowText的行数,其中包含问题和答案字符串,如数组(0 =>"question",1 =>"answer")等等.通过添加或删除行,XML文件内容可以变大或变小.我已经为此制作了"工作"功能.

Zee*_*ats 12

我已经解决了问题而不是hakre和互联网.所以对于有同样问题的人来说,这就是我解决它的方法.

    function getElementById($id) {
        $xpath = new DOMXPath($this->xmlDoc);
        return $xpath->query("//*[@id='$id']")->item(0);
    }
Run Code Online (Sandbox Code Playgroud)