我在制作一个函数来替换我的 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>
和我的 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);
}
$rowIds 是一个数组,其中包含修改 ans rowText 的行数,该数组包含问题和答案字符串,如 array(0=>"question",1=>"answer") 等等.通过添加或删除行,XML 文件内容可以变大或变小。我已经为此制作了“工作”功能。
最佳答案
我已经解决了问题,感谢 hakre 和互联网。因此,对于遇到同样问题的人,这就是我解决问题的方法。
function getElementById($id) {
$xpath = new DOMXPath($this->xmlDoc);
return $xpath->query("//*[@id='$id']")->item(0);
}
关于php xml dom getElementById 和 DOMXpath 查询获取元素失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210716/