Load and manipulate an XML file
In this tutorial we'll usephp.io.File class and Xml
Let's take the following xml file :
<root>
<user name="Cartman"/>
<user name="Kyle"/>
</root>
In PHP we'll proceed as following :
<?php
$xml = new DomDocument();
// $PATH = xml path
$xml->load($PATH);
// get an element (NodeElement)
$noeud_racine = $xml->getElementsByTagName('root')->item(0);
// get a list of elements (NodeList)
$utilisateurs = $xml->getElementsByTagName('users');
// create element
$nouvel_element = $xml->createElement('plop');
// navigate in nodeList
foreach($child as $utilisateurs)
{
// get an attribute value + displaying it
echo $child->getAttribute('name');
// add an attribut to an element
$child->setAttribute('age', '12');
// add a new node to another one
$child->appendChild($nouvel_element);
}
// save xml file
$xml->save($PATH);
?>
Here's how we'r going to proceed in haXe :
/*
- php.io.File.getContent($PATH) is used to get the content of a file
- Xml.parse(string) is used to parse our string in a valid Xml
*/
// get the XML file
var xml = Xml.parse(php.io.File.getContent(XML_PATH));
// get the node root (the very first one)
var noeud_racine = xml.firstElement();
// get its childs
var utilisateurs = noeud_racine.elements();
// create a new element
var nouvel_element = Xml.createElement('plop');
// navigate through them
for(child in utilisateurs)
{
// get an attribute value
trace(child.get('name'));
// set a new attribute value
child.set('age', '12');
// add a new child to our node
child.addChild(nouvel_element);
}
// save the xml file
php.io.File.putContent(XML_PATH, xml.toString());
If you download the source code, and test it, don't forget to check READ and WRITE rights.
Page(s) :
1
Contact
Follow me