首页 > 解决方案 > 使用 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 中更改它

我该怎么做?

标签: phpxml

解决方案


您的 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>

推荐阅读