/* Add Value of Property to an XML Document addval.sol A script to add an attribute and values to each element for a given tag of an XML file. Value may be taken from another XML document or any other source. (c) 2009 Scriptol.com MIT License - Use it freely Note: target file may be the source file, but an intermediate file, test.xml, is used for security remove the value of the targetfile variable to update directly the source file: text targetfile = "" */ include "dom.sol" text targetfile = "test.xml" void usage() print "Syntax" print " solp addval fname tname aname valfile" print "Attribute 'aname' is added to any 'tname' tag in the 'fname' XML file." print "Values are taken from same tags and properties in 'valfile'." print "The two XML files must share same IDs." exit(0) return /* Update attributes from id of elements and values in an array Input: - srcname: The XML filename - tgtname: The updated XML file (could be the same file) - tagid: Name of the attribute used for ID (may be 'id' or 'name' or anything else) - tname: The tagname to update - aname: The name of the attributes to update. Output: None. A new file is written. */ void addAttribute(text srcname, text tgtname, text tagid, text tname, text aname, array a) DOMDocument docsrc = DOMDocument("1.0") docsrc.load(srcname) DOMNodeList dnl = docsrc.getElementsByTagName(tname) int size = dnl.length DOMElement de = null int i = 0 while i < size de = dnl.item(i) text id = de.getAttribute(tagid) text value = a[id] if value != "" de.setAttribute(aname, value) /if let i + 1 docsrc.save(tgtname) return /* Build an associative array of values for a given property and tag Input: - valfile: The XML filename - tname: The name of the tags - tagid: The name of the property for the ID of an element - aname: The name of the attribute Output: - An associative array - keys: the ID of the tags - values: the values of the properties */ array getValues(text valfile, text tagid, text tname, text aname) DOMDocument docval = DOMDocument("1.0") docval.load(valfile) 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 /for return a int main(int argc, array argv) if argc < 4 ? usage() text fname = argv[1] text tname = argv[2] text aname = argv[3] text valfile = argv[4] if targetfile = "" let targetfile = fname print "Loading '$valfile', getting '$aname' values from '$tname' tags." array a = getValues(valfile, "id", tname, aname) print "Updating '$fname', adding '$aname' attributes and value to each matching '$tname' tag." addAttribute(fname, targetfile, "id", tname, aname, a) print "Type $targetfile to view the resulting file." return 1 main($argc, $argv)