php - 使用 php 读取和更改 xml 属性
问题描述
这是我的文件 xml 的一部分:
<office:body>
<office:text>
<text:sequence-decls>
<text:sequence-decl text:name="Illustration" text:display-outline-level="0"/>
<text:sequence-decl text:name="Table" text:display-outline-level="0"/>
<text:sequence-decl text:name="Text" text:display-outline-level="0"/>
<text:sequence-decl text:name="Drawing" text:display-outline-level="0"/>
</text:sequence-decls>
<text:p text:style-name="P2">pippo</text:p>
</office:text>
</office:body>
我想阅读“pippo”的“文本:样式名称”(示例中为 P2 ..)并在 P1 中更改它
我该怎么做?
解决方案
您的 XML 缺少命名空间定义(xmlns:* 属性)。它们真的很重要。我在答案中使用了虚拟命名空间 URI,但您必须将其替换为真实的 URI。
在 DOM 中,您可以使用 Xpath Xpath 表达式来获取特定节点,任何东西都是节点 - 元素、属性、文本内容......
$xml = <<<'XML'
<office:body xmlns:office="urn:office" xmlns:text="urn:text">
<office:text>
<text:sequence-decls>
<text:sequence-decl text:name="Illustration" text:display-outline-level="0"/>
<text:sequence-decl text:name="Table" text:display-outline-level="0"/>
<text:sequence-decl text:name="Text" text:display-outline-level="0"/>
<text:sequence-decl text:name="Drawing" text:display-outline-level="0"/>
</text:sequence-decls>
<text:p text:style-name="P2">pippo</text:p>
</office:text>
</office:body>
XML;
$document = new DOMDocument();
$document->loadXML($xml);
// create an Xpath instance and register the namespace
$xpath = new DOMXpath($document);
$xpath->registerNamespace('t', 'urn:text');
// fetch the "style" attribute of the "p" node with the text "pippo"
foreach ($xpath->evaluate('//t:p[text() = "pippo"]/@t:style-name') as $styleName) {
// attribute nodes have a value property that you can read and write
var_dump($styleName->value);
$styleName->value = 'P1';
}
echo $document->saveXML();
输出:
string(2) "P2"
<?xml version="1.0"?>
<office:body xmlns:office="urn:office" xmlns:text="urn:text">
<office:text>
<text:sequence-decls/>
<text:p text:style-name="P1">pippo</text:p>
</office:text>
</office:body>
推荐阅读
- sql-server - SQL 数据透视表
- machine-learning - 使用 LSTM 和 CNN 对 Keras 进行故障排除以进行时间序列分类
- php - 将 VB6 代码转换为 PHP - 字节作为参数?
- python - 基于动态列表从ini文件中检索多个配置键
- sql - 一个组的每小时总平均数
- powershell - 在 Powershell 中的同一个文本文件中写入和加载
- powershell - 创建远程打印机添加工具
- python - 使用 Dask to_datetime 和 Pandas 日期偏移
- python - 在加载模块时从模块返回
- vuetify.js - 如何确保 vuetify 的下拉菜单具有最高的 z-index?