/** * Converts the XML to Tree * is used to represent an empty string # is used for an empty list * These escape charectors will get removed from the file and will not effect the content of the * Tree. * * @param node * @return */ private static Tree xmlToTree(Node node) { NodeList nl = node.getChildNodes(); Node firstChild = nl.item(0); if (nl.getLength() > 0 && firstChild instanceof Text) { String text = ((Text) firstChild).getWholeText(); if (text.charAt(0) == STRING_ESCAPE) { return new Tree(text.substring(1)); } else if (text.charAt(0) == TREE_ESCAPE) { return new Tree(); } else { return new Tree(text); } } Tree t = new Tree(); for (int i = 0; i < nl.getLength(); i++) t.add(new Tree.Entry(nl.item(i).getNodeName(), xmlToTree(nl.item(i)))); return t; }
/** * Change a tree to a XML document. * is used to represent an empty string # is used for an empty * list These escape charactors will get added to the XML file and when reading gets taken out. * They will not have any effects on the contents of the XML file. * * @param tree * @param doc * @param node */ private static void treeToDOC(Tree tree, Document doc, Node node) { if (tree.isLeaf()) { String value = tree.value(); if (value.length() == 0 || value.charAt(0) == STRING_ESCAPE || value.charAt(0) == TREE_ESCAPE) { value = STRING_ESCAPE + value; } node.appendChild(doc.createTextNode(value)); } else { if (tree.size() > 0) { for (Tree.Entry t : tree.children()) { Node n = doc.createElement(t.name()); treeToDOC(t.tree(), doc, n); node.appendChild(n); } } else { node.appendChild(doc.createTextNode("" + TREE_ESCAPE)); } } }
/** * A helper method which calls tree.fromString(str). * * @param str * @return * @throws ParseException */ public Tree treeFromString(String str) throws ParseException { return Tree.fromString(str); }
/** * A helper method which calls tree.toString() * * @param tree * @return tree.toString() */ public static String treeToString(Tree tree) { return tree.toString(); }