Page 1 of 1
appendChild and DOM
Posted: Tue May 08, 2007 3:45 am
by user___
Hi guys,
I need to know how to append a child element to another child. This is the .xml file:
Code: Select all
...
<states>
<cities>
<quarters>
<street id="1" />
</quarters>
</cities
<states>
...
I need to append streets.
Posted: Tue May 08, 2007 6:56 am
by volka
Is there something to identify the "place" where you want to add a new element?
Reply
Posted: Tue May 08, 2007 7:25 am
by user___
No, there is just a tag and in quarters besides ids there are some more attributes.
BTW:The XML can be edited as it needs to be so if there should be something anywhere I can put it there.
Do you have any ideas of how to achieve this in Php?
Re: Reply
Posted: Tue May 08, 2007 7:41 am
by volka
user___ wrote:No, there is just a tag and in quarters besides ids there are some more attributes.
no but yes? attributes are good for identifying the location, e.g.
id, even the name says it.
With php5's dom extension you can do:
Code: Select all
$xml = <<< eox
<xml>
<states>
<cities>
<quarters id="6348">
<street id="1" />
</quarters>
</cities>
</states>
</xml>
eox;
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$nodeset = $xpath->query('//quarters[@id=6348]');
if ( 1!=$nodeset->length ) {
echo 'error: ', $nodeset->length, ' quarters found';
}
else {
$newElement = $dom->createElement('street');
$newElement->setAttribute('id', '45');
$nodeset->item(0)->appendChild($newElement);
}
echo $dom->saveXML();
Relply
Posted: Tue May 08, 2007 8:07 am
by user___
Thank you, volka but I need a little modification in this script and it will suit my needs at all. Well, is it possible to get the last id(I mean not 6348 but if there are 9393 ids to get 9393 as a result).
Is this possible or is there a workaround to get the last id and then append it on it.