开发者

PHP: XML parsing question

开发者 https://www.devze.com 2023-01-27 07:31 出处:网络
I\'m using SimpleXML for parsing XMl documents. I need to be able to read/update node attributes. In this XML document

I'm using SimpleXML for parsing XMl documents. I need to be able to read/update node attributes.

In this XML document

<root>
  <node>ABC</node>
  <key>123</key>
  <node2>
     <key>456</key>
  <开发者_StackOverflow;/node2>
  <key>789</key>
</root>

How can I read/update all key nodes? the document doesn't have a specific structure, so I need to be able to find them without knowing their position. Let's say I want to multiply by 2 the numbers in the key nodes. How can I do it?

Tks.


I find the question extremely lazy, but anyway

$sxe = new SimpleXmlElement($xml);
foreach($sxe->xpath('//key') as $key) $key[0] *= 2;
echo $sxe->asXML();

There is plenty of questions about SimpleXml on Stack Overflow. Please search for them before asking your question. The PHP Manual also has examples covering Basic Usage.


<?php

$xml = '<root>
  <node>ABC</node>
  <key>123</key>
  <node2>
     <key>456</key>
  </node2>
  <key>789</key>
</root>';

$dom = new DOMDocument();
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
foreach ($xpath->query('//text()') as $node)
{
 $newNode = $dom->createDocumentFragment();
 $newNode->appendXML($node->wholeText . ' replaced');
 $node->parentNode->replaceChild($newNode, $node);
}

echo $dom->saveXML();


The simplest possible API is QueryPath (or phpQuery):

$qp = qp($xml);

foreach ($qp->find("key") as $key) {
     //@todo: add verification that it's indeed numeric text
     $key->text(  $key->text() * 2  );
}

But something similar is possible with "SimpleXML"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号