【发布时间】:2017-10-28 06:57:28
【问题描述】:
我正在尝试将 XML 文件分成两个文件,longrentals.xml 和 shortrentals.xml,但遇到了我遇到的最后一个障碍。以下是我希望发生的事情:
- rentals.xml 被解析,并且对于 term = "short" 的每个实例,该条目的顶部父 "property" 节点被保存到 shortrentals.xml。
- 从rentals.xml 文件中删除每个实例(提取后)。
- shortrentals.xml 文件已保存。
- 原始文件中的其余条目保存到 longrentals.xml。
XML结构如下:
<property>
...
<rent>
<term>short</term>
<freq>week</freq>
<price_peak>5845</price_peak>
<price_high>5845</price_high>
<price_medium>4270</price_medium>
<price_low>3150</price_low>
</rent>
...
</property>
我使用的代码如下:
$destination = new DOMDocument;
$destination->preserveWhiteSpace = true;
$destination->loadXML('<?xml version="1.0" encoding="utf-8"?><root></root>');
$source = new DOMDocument;
$source->load('file/rentals.xml');
$xp = new DOMXPath($source);
$destRoot = $destination->getElementsByTagName("root")->item(0);
foreach ($xp->query('/root/property/rent[term = "short"]') as $item) {
$newItem = $destination->importNode($item, true);
$destRoot->appendChild($newItem);
$item->parentNode->removeChild($item);
}
$source->save("file/longrentals.xml");
$destination->formatOutput = true;
$destination->save("file/shortrentals.xml");
除了 shortrentals.xml 中的输出仅包含出租节点而不包含顶级父属性节点之外,此方法有效。此外,从 longrentals.xml 中删除的条目仅删除了 Rent 子节点。那么,请问如何使用我的代码升级?
【问题讨论】:
标签: php xml domdocument