
The sjg.xml package
The sjg.xml package is less than 10 KB. It is fairly fast: I think it can process around 1-2 MB/sec on my 300 Pentium II.
The package consists of the following classes:
Document: Represents an XML-document. You will want to
access the root element via the getRoot() method.Element: Represents an XML-element. Use elements() or elements(name)
to iterate thru the contents of the element and use getAttribute(name)
to read an attribute.Comment: Represents an XML-comment.ProcessingInstruction: Represents an XML processing instruction.Data: Represents an XML data chunk.Attribute: Represents an XML-attribute. Get its value as
string, int or double using getValue(), getIntValue() or getDoubleValue().Parser: Responsible for parsing a textual representation
of an xml-document. Use parse(URL) or parse(text).Tokenizer: Splits an xml-text into tokens parsed by the
parser.Tasks
Parsing an xml-document:
From a string:
Document document =
Parser.parse("<?xml version=\"1.0\" standalone=\"yes\"><aloha-xml/>");
From an input stream of the server an applet is served from:
Document document = Parser.parse(new URL(getDocumentBase(), "SomeServlet"));
Deserializing objects from sjg.xml.Document - we have some stocks in an XML-file like this:
<market>
<stock name="microsoft" value="42" volume="1000">
...
</market>
We want to parse that into some stock objects:
Element market = document.getRoot();
Hashtable stocks = new Hashtable();
if (market.getName().equals("market"))
for (Enumeration e = market.elements("stock"); e.hasMoreElements();
) {
Element element = (Element)e.nextElement();
stocks.put(element.getAttribute("name").getValue(),
new Stock(element.getAttribute("price").getIntValue()),
element.getAttribute("volume").getIntValue());
}
Getting the textual representation of an element or a document - just use toString():
Document document = new Document(myElement);
System.out.println(document.toString());
What is missing?
A lot: Schema validation, processing instructions etc. For this you would want to use e.g. jdom. This parser will never be able to these things.
Demonstrations
The link graph on my wiki uses the parser to make remote procedure calls between the wiki server and the downloaded link graph applet. The games on vredungmand.dk uses the parser to read the configuration file that contains the levels, mazes and scripts.
Download