我想完全删除size="id"
来自每个 <door>
的属性元素。
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249" size="30"/>
<door id="1041" entry="6523" size="3094"/>
-- and 1000 more....
</doors>
PHP 代码:
$xml = new SimpleXMLElement('http://mysite/doors.xml', NULL, TRUE);
$ids_to_delete = array( 1, 1506 );
foreach ($ids_to_delete as $id) {
$result = $xml->xpath( "//door[@size='$id']" );
foreach ( $result as $node ) {
$dom = dom_import_simplexml($node);
$dom->parentNode->removeChild($dom);
}
}
$xml->saveXml();
我没有收到错误,但它不会删除尺寸属性。为什么?
最佳答案
I get no errors but it does not delete the size attribute. Why?
它不删除尺寸属性的原因有多种。我首先想到的是属性不是子节点。使用删除子项的方法不适合删除属性。
Each element node has an associated set of attribute nodes; the element is the parent of each of these attribute nodes; however, an attribute node is not a child of its parent element.
来自: Attribute Nodes - XML Path Language (XPath),我加粗了。
但是,您在这里看不到错误,因为您的 $result
是一个空数组。您只是不使用 xpath 选择要删除的任何节点(既不是元素也不是属性)。那是因为没有您要查找的此类元素:
//door[@size='1']
您正在尺寸属性中搜索 ID:不匹配。
以下是您没有收到错误且不会删除任何尺寸属性的原因:1.) 您不会在此处删除属性,2.) 您不会查询任何元素来从中删除属性。
如何删除Xpath查询的SimpleXML中的属性?
您可以通过使用 Xpath 查询选择属性节点来删除它们,然后取消设置 SimpleXMLElement self-reference :
// all size attributes of all doors
$result = $xml->xpath("//door/@size");
foreach ($result as $node) {
unset($node[0]);
}
在此示例中,所有属性节点都通过 Xpath 表达式进行查询,这些表达式是门元素的大小属性(这是您在问题中所要求的),然后将它们从 XML 中删除。
//door/@size
(参见 Abbreviated Syntax)
现在是完整的示例:
<?php
/**
* @link https://eval.in/215817
*/
$buffer = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249" size="30"/>
<door id="1041" entry="6523" size="3094"/>
-- and 1000 more....
</doors>
XML;
$xml = new SimpleXMLElement($buffer);
// all size attributes of all doors
$result = $xml->xpath("//door/@size");
foreach ($result as $node) {
unset($node[0]);
}
$xml->saveXml("php://output");
输出(Online Demo):
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249"/>
<door id="1041" entry="6523"/>
-- and 1000 more....
</doors>
关于php - 删除 XML 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26655178/