-1

我正在尝试使用 PHP 在 XML 文件中附加一些数据。

我正在搜索一个词是否已经存在于 XML 中。

如果它存在,我只需要将数据附加到它,否则我必须创建整个元素。

为此,我正在使用 DOMXPath。代码如下:

$fname="ontology.xml";  

$xml=new DomDocument;
$xml->Load($fname);

$xpath = new DOMXPath($xml);

$query = '//RelatedTerms/words/word/word_title[.="'.$word.'"]';

$entries=$xpath->query($query);

 if($entries->length!=0)
{   
    foreach($entries as $entry)
    {
        $wordElement=$xml->getElementsByTagName($entry->parentNode->nodeName)->item(0);
//Problem is here even if the <word> is found at the second position it append the element to the first <word> element.

            $newIsaElement=$xml->createElement('isa');
            $newIsaTitleElement=$xml->createElement('isa_title',"sample");
            $newRelevanceTitle=$xml->createElement('relevance',"9");

            $newIsaElement->appendChild($newIsaTitleElement);
            $newIsaElement->appendChild($newRelevanceTitle);

            //$newIsaTitleElement->appendChild($newIsaElement);
            $wordElement->appendChild($newIsaElement);
            $xml->save($fname); 

    }
}
else
{
    echo "In Here!";        

    $words=$xml->getElementsByTagName('words')->item(0);
    $newWordElement=$xml->createElement('word');
    $newWordTitleElement=$xml->createElement('word_title',$word);
    $newIsaElement=$xml->createElement('isa');
    $newIsaTitleElement=$xml->createElement('isa_title',"test");
    $newRelevanceTitle=$xml->createElement('relevance',"2");

    $newWordElement->appendChild($newWordTitleElement);
    $newIsaElement->appendChild($newIsaTitleElement);
    $newIsaElement->appendChild($newRelevanceTitle);
    $newWordElement->appendChild($newIsaElement);

    $words->appendChild($newWordElement);

    $xml->save($fname);
}

我想将该元素添加到找到该单词的同一元素中。请帮我解决这个问题!

谢谢!

PS:如果需要,这里是xml文件的格式!

<RelatedTerms>
<words>
    <word>
        <word_title>algo</word_title>
        <isa>
            <isa_title>algorithm</isa_title>
            <relevance>9</relevance>
        </isa>
        <hasa>
            <hasa_title>Algorithmic Example</hasa_title>
            <relevance>7</relevance>
        </hasa>
        <akindof>
            <akindof_title>Pseudo Code</akindof_title>
            <relevance>8</relevance>
        </akindof>
        <partof>
            <partof_title>Data Structures</partof_title>
            <relevance>9</relevance>
        </partof>
    </word>
            <word>
                   <word_title>algo</word_title>
                   <isa>
                      <isa_title>test</isa_title>
                       <relevance>9</relevance> //instead of adding it here it adds to the above element
                    </isa>
            </word>
</words>

4

1 回答 1

2

$entries不是一个数组,它是一个 DOMNodeList 对象。用 . 检查是否为空$entries->length == 0

于 2012-05-25T07:02:42.590 回答