使用php

时间:2018-06-04 22:39:26

标签: 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>
&#13;
&#13;
&#13;

我想阅读&#34; text:style-name&#34;为&#34; pippo&#34; (示例中为P2 ..)并在P1中更改

我该怎么做?

1 个答案:

答案 0 :(得分:0)

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