Script to Add Attributes to XML Tags

To avoid the repetitive task of manually add the same attribute for all elements of the same level in a XML file, use this script in PHP 5, which requires 3 parameters.

With the first script, addatt, the values of the attribute will be added manually.
A second script, addval, reads the values in an array created from an XML file.

Adding attributes without values

For example, to this document:

    <car name="xxx" /> 
    <car name="yyy" />

We will automatically add the attribute "speed" to the tag "car".

     <car name="xxx" speed="80" /> 
     <car name="yyy" speed="90" />

Using the script

It requires three parameters

The command has the following form:

solp addatt fname tname aname

The new XML document is saved as test.xml.
You have then to delete the original file to rename test.xml under its name.

The scriptol code

DOMDocument docsrc = DOMDocument("1.0")
docsrc.load(filename) DOMNodeList dnl = docsrc.getElementsByTagName(tname)
DOMElement de = null int i = 0 while i < dnl.length
de = dnl.item(i)
de.setAttribute(aname, "")
let i + 1

The PHP code

$docsrc=new DOMDocument("1.0");

$i = 0;
$de->setAttribute($aname,""); $i+=1; } $docsrc->save($filename);

Adding attributes with values

Using the script

A last parameter is added: the name of the XML file where the values are read.

The code

The previous function is modified to read the values in an array and assign them to the elements.

This implies that the elements have an identifier which is also in the table. To do this we create an associative array with the id as key and for the value that of the attribute.

Reading values in an XML file

DOMNodeList dnl = docval.getElementsByTagName(tname)	
DOMElement de = null array a = {} for int i in 0 -- dnl.length
de = dnl.item(i) text id = de.getAttribute(tagid) // get the ID
text value = de.getAttribute(aname) // get the value of the property for this ID a[id] = value

Assigning values to XML elements

while i < size
de = dnl.item(i)
text id = de.getAttribute(tagid)
de.setAttribute(aname, a[id])
let i + 1

This time, the attributes are assigned according to the tag name and the identifier of the element that should be the key in the table.

Download source codes (Scriptol/PHP)