I have some XML to开发者_运维问答 which I need to add a child.
Using SimpleXML, I'm not having any issue adding a simple node.
The beginning XML looks a bit like this:
<root>
<item>
<title>This is the title</title>
<sort>2</sort>
</item>
<item>
<title>This is another title</title>
<sort>3</sort>
</item>
</root>
I need to add a node that looks like this:
<label id=1>
<title type=normal>This is a label</title>
<sort>1</sort>
</label>
The result would be:
<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>
I'm able to add a simple child using:
$xml->root->addChild('label', 'This is a label');
I am having trouble getting the attributes and children added to this newly added node though.
I am not worried about appending versus prepending as the sorting happens in XSLT.
addChild returns the added child, so you just have to do :
$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);
$xml->root->addChild('label', 'This is a label');
This opereration returns a reference to the child that was just added. So you could do this:
$child = $xml->root->addChild('label', 'This is a label');
From this, you can not add your additional children and attributes to that child.
$child->addAttributes('id', '1');
Since it returns a reference, that node and attributes that were just added are part of the $xml object as well.
精彩评论