【发布时间】: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/>
您知道为什么它可能不起作用吗?
【问题讨论】: