php文档xml过滤元素
我已经花了半天时间了。但不是专家。为什么用php遍历和操作xml比在纸上处理数据更难(看起来是这样)?为什么不能有一个像jQuery这样的简单系统来解决这个问题呢?php文档xml过滤元素,php,xml,domdocument,Php,Xml,Domdocument,我已经花了半天时间了。但不是专家。为什么用php遍历和操作xml比在纸上处理数据更难(看起来是这样)?为什么不能有一个像jQuery这样的简单系统来解决这个问题呢? 我一直试图根据一个简单的条件从一个长列表(580个元素)中删除一些元素:if(element['attr']==value){remove element},但我没有做到这一点。 这是我的代码: $xml = simplexml_load_file('xml/suchia.xml'); $dom = new DOMDocument(
我一直试图根据一个简单的条件从一个长列表(580个元素)中删除一些元素:
if(element['attr']==value){remove element}
,但我没有做到这一点。这是我的代码:
$xml = simplexml_load_file('xml/suchia.xml');
$dom = new DOMDocument('1.0');
$dom->loadXML($xml->asXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
foreach ($dom->getElementsByTagName('image') as $node) {
echo 'Checking '.$node->getAttribute('id').'<br />';
if ($node->getAttribute('value') == 'useless') {
echo $node->getAttribute('id').' deleted.<br />';
$node->parentNode->removeChild($node);
}
}
$dom->save('xml/suchia.xml');
$xml=simplexml\u load\u文件('xml/suchia.xml');
$dom=新的DOMDocument('1.0');
$dom->loadXML($xml->asXML());
$dom->preserveWhiteSpace=false;
$dom->formatOutput=true;
foreach($dom->getElementsByTagName('image')作为$node){
回显“正在检查”。$node->getAttribute('id')。
;
如果($node->getAttribute('value')=='无用'){
echo$node->getAttribute('id')。已删除。
;
$node->parentNode->removeChild($node);
}
}
$dom->save('xml/suchia.xml');
我从第一个回音中看到的主要问题是foreach并没有遍历它看起来的每个元素。对于较长的列表(我的is xml文件大约有180000个字符),siple循环似乎是不可能的
XML(缩写,可能无法用一个小XML文件重建我的问题):
A.
B
C
D
E
F
G
H
因为在通过live DOMNodeList进行迭代时要从父节点删除节点,所以迭代器只能看到其他节点。正如Ghost所建议的,使用XPath允许在删除节点的同时进行迭代
如果在适当的位置设置了preserveWhiteSpace
(需要在解析XML之前设置它,而formatOutput
仅适用于输出),那么额外的空白将不会出现在输出中
<?php
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->load('input.xml');
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('image[@value="useless"]');
printf("Removing %d useless images\n", $nodes->length);
foreach ($nodes as $node) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
$doc->save('output.xml');
query('image[@value=“无用”]”);
printf(“删除%d个无用图像\n”,$nodes->length);
foreach($node作为$node){
$node->parentNode->removeChild($node);
}
$doc->formatOutput=true;
$doc->save('output.xml');
<?php
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->load('input.xml');
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('image[@value="useless"]');
printf("Removing %d useless images\n", $nodes->length);
foreach ($nodes as $node) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
$doc->save('output.xml');