2011-04-19 66 views
3

我有一些XML我需要添加一个孩子。SimpleXML添加孩子和属性

使用SimpleXML,我没有任何问题添加一个简单的节点。

的开始XML看起来有点像这样:

<root> 
    <item> 
     <title>This is the title</title> 
     <sort>2</sort> 
    </item> 
    <item> 
     <title>This is another title</title> 
     <sort>3</sort> 
    </item> 
</root> 

我需要补充的是这样的一个节点:

<label id=1> 
     <title type=normal>This is a label</title> 
     <sort>1</sort> 
    </label> 

其结果将是:

<root> 
    <item> 
     <title>This is the title</title> 
     <sort>2</sort> 
    </item> 
    <item> 
     <title>This is another title</title> 
     <sort>3</sort> 
    </item> 
    <label id=1> 
     <title type=normal>This is a label</title> 
     <sort>1</sort> 
    </label> 
</root> 

我可以添加一个简单的孩子使用:

$xml->root->addChild('label', 'This is a label'); 

虽然我无法获取属性和子添加到这个新添加的节点。

我不担心在XSLT中进行排序时追加与预先计划相关。

+2

你想要做什么说明书中加以说明。 http://docs.php.net/manual/en/simplexml.examples-basic.php(示例#10) – 2011-04-19 16:33:24

回答

11

的addChild返回添加的孩子,所以你只需要做:

$label = $xml->root->addChild('label'); 
$label->addAttribute('id', 1); 
$title = $label->addChild('title', 'This is a label'); 
$title->addAttribute('type', 'normal'); 
$label->addChild('sort', 1); 
+0

感谢切割/粘贴能力 - 时间紧迫。这正是我所期待的。 – ropadope 2011-04-19 14:53:06

1
$xml->root->addChild('label', 'This is a label'); 

此操作返回刚刚添加的孩子的引用。所以,你可以这样做:

$child = $xml->root->addChild('label', 'This is a label'); 

这个,你不能加入你额外的儿童和属性那个孩子。

$child->addAttributes('id', '1'); 

由于它返回一个引用,只是补充说,节点和属性是$ XML对象的一部分。

+0

它是如何工作的很好的解释。 – ropadope 2011-04-19 14:52:37