首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在不使用父对象的情况下设置SimpleXmlElement的文本值?

如何在不使用父对象的情况下设置SimpleXmlElement的文本值?
EN

Stack Overflow用户
提问于 2010-07-01 05:17:39
回答 1查看 21.8K关注 0票数 23

我想设置xpath()找到的某个节点的文本

代码语言:javascript
复制
<?php

$args = new SimpleXmlElement(
<<<XML
<a>
  <b>
    <c>text</c>
    <c>stuff</c>
  </b>
  <d>
    <c>code</c>
  </d>
</a>
XML
);

// I want to set text of some node found by xpath 
// Let's take (//c) for example

// convoluted and I can't be sure I'm setting right node
$firstC = reset($args->xpath("//c[1]/parent::*")); 
$firstC->c[0] = "test 1";

// like here: Found node is not actually third in its parent.
$firstC = reset($args->xpath("(//c)[3]/parent::*")); 
$firstC->c[2] = "test 2";

// following won't work for obvious reasons, 
// some setText() method would be perfect but I can't find nothing similar, 
$firstC = reset($args->xpath("//c[1]"));
$firstC = "test"; 

// maybe there's some hack for it?
$firstC = reset($args->xpath("//c[1]"));
$firstC->{"."} = "test"; // nope, just adds child named .
$firstC->{""} = "test"; // still not right, 'Cannot write or create unnamed element'
$firstC["."] = "test"; // still no luck, adds attribute named .
$firstC[""] = "test"; // still no luck, 'Cannot write or create unnamed attribute'
$firstC->addChild('','test'); // grr, 'SimpleXMLElement::addChild(): Element name is required'
$firstC->addChild('.','test'); // just adds another child with name .

echo $args->asXML();

// it outputs:
// 
// PHP Warning:  main(): Cannot add element c number 2 when only 1 such elements exist 
// PHP Warning:  main(): Cannot write or create unnamed element 
// PHP Warning:  main(): Cannot write or create unnamed attribute 
// PHP Warning:  SimpleXMLElement::addChild(): Element name is required 
// <?xml version="1.0"? >
// <a>
//  <b>
//   <c .="test">test 1<.>test</.><.>test</.></c>
//   <c>stuff</c>
//  </b>
//  <d>
//   <c>code</c>
//  <c>test 2</c></d>
// </a>
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3153477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档