Download Latest version
Transcript
public static void main (String args[]) {
PersonSort1 person = new PersonSort1();
person.run("person.xml");
}
private void run(String filename){
try {
dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filename);
Element e = dom.getDocumentElement();
dom.replaceChild(sort(e),e);
Transformer transform = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new File("Sorted.xml"));
transform.transform(new DOMSource(dom), result);
} catch (Exception e) {
e.printStackTrace();
}
}
The mapping has to be initialized in the following ways:
• the importation of org.w3c.dom.* and javax.xml.* packages in order to use the DOM library.
• the %include{ dom.tom } construct imports the definition of Tom algebraic constructors needed
to manipulate DOM objects.
• the dom variable has to be instantiated. This variable corresponds to the notion of Document in
the DOM terminology.
2.2.2
Comparing two nodes
In order to implement a sorting algorithm, we need to know how to compare two elements.
The following function takes two Xml documents in argument and compares their attribute Age,
using the string comparison operator compareTo.
private int compare(Node t1, Node t2) {
%match(TNode t1, TNode t2) {
<Person Age=a1></Person>, <Person Age=a2></Person> -> { return ‘a1.compareTo(‘a2); }
}
return 0;
}
In this example, it is interesting to note that an Xml node is seen as an associative operator. This
feature, combined with the implicit notation, is such that <Person Age=a1></Person> will match any
Xml node headed by Person which contains the attribute Age. This Xml node may contain several
sub-nodes, but they will not be stored in any variable.
2.2.3
Sorting a list of nodes
In this section we use a swap sort algorithm which consists in finding two elements that are not in the
correct order. Once they are found, they are swapped before calling the algorithm recursively. When no
two such elements exist, this means that the list is sorted.
private Node sort(Node subject) {
%match(TNode subject) {
<Persons>(X1*,p1,X2*,p2,X3*)</Persons> -> {
if(compare(‘p1,‘p2) > 0) {
21