BUG XML HOWTO
From BUG Wiki
This page describes using the simple XML parser that is embedded in the BUG OSGi Common bundle. This XML parser is used throughout the BUGbase code.
This DOM-style parser was written to be simple and small. Namespaces are ignored. Schema validation is not implemented. JDOM or other standard Java XML interfaces are not used. Any code you write against this parser will not work with another XML parser. That said, for simple XML handing it works quite well.
The parser is based on an old JavaWorld.com article. There are several of these running around, and now looking back I can't seem to find the actual article it's based on. From there it was cleaned up a bit and modernized. A simple XPath query engine is available as well.
This is the class that models an XML Node. These can be created ad-hoc and attached to other XmlNodes. Javadoc is here.
This class provides a static method to parse a string or Reader into a DOM. Returned is the root XmlNode of the parsed XML. Javadoc is here.
This class allows simple queries to be executed against a given DOM. Javadoc is here.
Creating an XML document code-style
XmlNode root = new XmlNode("root"); new XmlNode(root, "Child 1"); new XmlNode(root, "Child 2");
Resulting XML root.toString():
<root> <Child 1/> <Child 2/> </root>
Parsing an XML document from a String
String s = "<root><c1></c1><c2></c2></root>"; XmlNode root = XmlParser.parse(s); System.out.println(root.toString());
The result should be:
<root> <c1></c1> <c2></c2> </root>
Accessing Nodes and attributes
String s = "<root><c1 at1=\"v1\"></c1><c2></c2></root>"; XmlNode root = XmlParser.parse(s); System.out.println(root.getChild("c1").getAttribute("at1"));
Executing a XPath Query
String s = "<root><c1 at1=\"v1\"></c1><c2>c2 value</c2></root>"; XmlNode root = XmlParser.parse(s); XmlNode result = (XmlNode) XpathQuery.evaluate("/root/c1", root, XpathQuery.NODE); System.out.println(result.toString());
Take a look at the projects com.buglabs.common and com.buglabs.common.tests for the source. The tests bundle has a class, XMLParseTests that exercises the parser.