【问题标题】:Can't save to XML file using domXML无法使用 domXML 保存到 XML 文件
【发布时间】:2012-03-15 18:18:01
【问题描述】:

我一直在尝试创建一种在 XML 文件中添加新元素的方法,但由于某种原因它不会修改元素,即使当我使用 saveXML 打印正确的元素时也是如此。

function fnDOMEditElementCond($product_id, $name, $weight, $category, $location) {

        if (!isset($product_id) || is_numeric($product_id)) {
          return false;
      }
        $obj = new helperClass();
        $xmlDoc = $obj->fetchFromXMLDocument('storage.xml');
        $xpath = new DOMXPath($xmlDoc);

        $result = $xpath->query(sprintf('/storagehouse/item[@id="%s"]', $product_id));
        if (!$result || $result->length !== 1) {
            throw new Exception(sprintf('Item with id "%s" does not exists or is not unique.', $product_id));
        }
        $item = $result->item(0);
       //Change the name element
        $xName = $xpath->query("./name", $item)->item(0);
        $xName->removeChild($xName);

//        //Change the name element
//        $xWeight = $xpath->query("./weight", $item)->item(0);
//        $xWeight->nodeValue = $weight;
//        
//        //Change the name element
//        $xLocation = $xpath->query("./location", $item)->item(0);
//        $xLocation->nodeValue = $category;
//        
//        //Change the name element
//        $xCategory = $xpath->query("./category", $item)->item(0);
//        $xCategory->nodeValue = $location;








        echo $xmlDoc->saveXML($item);
    }

}

此代码采用一个 ID,并根据 id 修改信息,包括四个元素。

这里是xml文件

storagehouse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:noNamespaceSchemaLocation="schema.xsd">
    <item id="c7278e33ef0f4aff88da10dfeeaaae7a">
        <name>HDMI Cable 3m</name>
        <weight>0.5</weight>
        <category>Cables</category>
        <location>B3</location>
    </item>
    <item id="df799fb47bc1e13f3e1c8b04ebd16a96">
        <name>Dell U2410</name>
        <weight>2.5</weight>
        <category>Monitors</category>
        <location>C2</location>
    </item>
    <item id="53abbd89766ea8759b5ebe5bacd43f58">
        <name>HP Probook 1311</name>
        <weight>2.1</weight>
        <category>Notebooks</category>
        <location>A1</location>
    </item>
<storagehouse/>

您知道为什么它可能不起作用吗?

【问题讨论】:

    标签: php xml dom xpath


    【解决方案1】:

    我相信这是因为您正在寻找 save() 而不是 savexml()。你需要给 save() 文件名。

    编辑:另外,如果我没记错的话,每次保存后都需要重新加载 DOM,否则只会影响未保存的 DOM 元素。但自从我不得不这样做以来已经有一段时间了。我将查看我的旧代码以仔细检查。

    再次编辑:我一直在查看我的代码,这似乎是必要的。您可以一次完成所有需要的修改,但如果您需要在中间查看结果,则必须使用 saveXML() 或 save() 生成它并将其读入新的 XML 对象。原始对象只会反映原始内容。我没有像我应该的那样在我的 cmets 中正确地注意到它,但是我的代码是以这样一种方式完成的,它让我认为我是对的。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多