php - 删除 XML 中的属性

标签 php xml

我想完全删除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/

相关文章:

php - 将 MySQL 查询转换为 Laravel (5.5) 查询生成器

java - 使用java向远程服务发送xml请求

Android MaterialButton 不会在 android lollipop 中以编程方式更改它的颜色

sql-server - 如何在 XML 中转换聚合函数

php - 在 Codeigniter 中从 Excel 导入时,无法使用 where 子句选择数据

python - 从Python到PHP的for循环转换问题

php - Laravel 中 "Resource"路由的不同策略

php - 我的问题从未解决,无法在 laravel 框架中上传大于 2M 的文件

xml - Oracle 10.1 和 11.2 使用相同的语句生成不同的 XML

xml - 我怎样才能从 xsd 序列中删除排序