You are viewing outdated content for BUG. If you have a BUG Y.T. edition or 2.0 series device, please visit our updated wiki: http://wiki.buglabs.net



BUG XML HOWTO

From BUG Wiki

Jump to: navigation, search

Contents

Overview

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.

Caveats

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.

History

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.

Classes

XmlNode

This is the class that models an XML Node. These can be created ad-hoc and attached to other XmlNodes. Javadoc is here.

XmlParser

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.

XpathQuery

This class allows simple queries to be executed against a given DOM. Javadoc is here.

Examples

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"));

This returns:

v1

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());

Results:

<c1 at1="v1"></c1>

Further Reading

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.