0

我正在尝试学习如何使用 Php XML DOM 来访问 XML 文件并更改原子值。我以前没有做过这样的事情,虽然我在网上找到了很多类似的案例,但我还没有设法找到解决方案。这就是我所拥有的:

  <?php
   $dom = new DOMDocument;
   $dom->load('getobs.xml');

   $xpath = new DOMXPath($dom);
   $nodeList = $xpath->query("//beginPosition");
   $nodeList->item(0)->nodeValue .= '546';

   $dom->saveXML();
   ?>

所以,我在上面的代码中试图做的是:1)加载一个xml文件。2) 将元素“beginPosition”的值更改为“546”

在整个 XML 文件中,只有一个具有此名称的元素 (beginPosition)。你能告诉我我做错了什么吗?

谢谢。迪特里斯

4

2 回答 2

0

最后我设法通过使用以下代码来做到这一点:

    <?php
    // create new DOM document and load the data
    $dom = new DOMDocument;
    $dom->load('getobs.xml');
    //var_dump($dom);
    // Create new xpath and register the namespace
    $xpath = new DOMXPath($dom);
    $xpath->registerNamespace('g','http://www.opengis.net/gml');
    // query the result amd change the value to the new date
    $result = $xpath->query("//g:beginPosition");
    $result->item(0)->nodeValue = 'sds';
    // save the values in a new xml
    file_put_contents('test.xml',$dom->saveXML());
    ?>

错误是我没有注册命名空间!

于 2013-03-27T11:43:43.303 回答
0

您没有将结果保存回文件。saveXML()是一个命名错误的方法,它以 xml 形式返回结果,它不会将其保存回文件中。

保存XML

将最后一行更改为

 file_put_contents('getobs.xml',$dom->saveXML());
于 2013-03-26T13:57:55.343 回答