【发布时间】:2012-03-12 16:50:10
【问题描述】:
您好,我知道这里有很多关于将这三个主题组合在一起以更新 XML 条目的问题,但似乎每个人都对特定问题非常具体。
我已经花了一些时间试图了解 XPath 及其方式,但我仍然无法得到我需要做的事情。
我们来了
我有这个 XML 文件
<?xml version="1.0" encoding="UTF-8"?>
<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>
</storagehouse>
我想做的是在需要时更新/编辑上面的任何节点。我会为此做一个 Html 表单。 但是我最大的问题是如何找到并更新所需的节点并进行更新?
这里有一些我想做的事情
<?php
function fnDOMEditElementCond()
{
$dom = new DOMDocument();
$dom->load('storage.xml');
$library = $dom->documentElement;
$xpath = new DOMXPath($dom);
// I kind of understand this one here
$result = $xpath->query('/storagehouse/item[1]/name');
//This one not so much
$result->item(0)->nodeValue .= ' Series';
// This will remove the CDATA property of the element.
//To retain it, delete this element (see delete eg) & recreate it with CDATA (see create xml eg).
//2nd Way
//$result = $xpath->query('/library/book[author="J.R.R.Tolkein"]');
// $result->item(0)->getElementsByTagName('title')->item(0)->nodeValue .= ' Series';
header("Content-type: text/xml");
echo $dom->saveXML();
}
?>
有人可以给我一个带有属性等的示例,因此用户决定更新所需的节点,我可以使用 XPath 找到该节点然后更新它吗?
【问题讨论】:
-
storagehouse是根元素 (/) 我相信,所以你不应该使用/storagehouse,而应该使用/。