StaxMate Tutorial

As per introduction, StaxMate is designed to allow

To see what this means in action, let's have a look at simple sample use cases.

Writing an XML document

Let's start with a particular simple and common use case: that of writing (aka generating) XML content. Content can come from variety of sources; here we only consider generation, not where data comes from.

Let's say we want to output XML document like this one:

   1 <!-- generated: [CURRENT TIME]-->
   2 <employee id="123">
   3   <name>
   4     <first>Tatu</first>
   5     <last>Saloranta</last>
   6   </name>
   7 </employee>

Let's first look at one possible piece of code to output such a document:

   1 // 1: need output factory
   2 SMOutputFactory outf = new SMOutputFactory(XMLOutputFactory.newInstance());
   3 SMOutputDocument doc = outf.createOutputDocument(new File("empl.xml"));
   4 // (optional) 3: enable indentation (note spaces after backslash!)
   5 doc.setIndentation("\n  ", 1, 1);
   6 // 4. comment regarding generation time
   7 doc.addComment(" generated: "+new java.util.Date().toString());
   8 SMOutputElement empl = doc.addElement("employee");
   9 empl.addAttribute(/*namespace*/ null, "id", 123);
  10 SMOutputElement name = empl.addElement("name");
  11 name.addElement("first").addCharacters("Tatu");
  12 name.addElement("last").addCharacters("Saloranta");
  13 // 10. close the document to close elements, flush output
  14 doc.closeRoot();

So how does that work? Here is what is being done and why:

  1. First we create a StaxMate output factory: here we use automatic introspection that Stax XMLOutputFactory offers (to find any plugged implementation)

    • This output factory is full thread-safe (after configuration), and should be reused: usually a single(ton) instance is enough for the whole application or service.
  2. Create the document output object. Document object just denotes document itself, not a root element: but we will add the root element under it (could also add comments, processing instructions). In this case, we will write an xml file.
  3. We can also choose to "pretty print" output document, by enabling indentation.
  4. It is often useful to add xml comments that include developer-readable information about generator process; it is easily ignored by xml readers
  5. Add Employee element
  6. Add attribute 'id' with typed value (StaxMate can convert from number to String)

  7. Add 'name' element
  8. Add both 'first' element and its textual contents
    • (note: in Woodstox 2.0 could use "name.addElementWithCharacters()" to simplify this!)
  9. Add similarly, 'last' and its textual contents
  10. Important: MUST close the root-level object; otherwise start elements may not get closed, contents not flushed to the file.

Some things to consider:

Reading XML content

Now that we have written some XML content, let's read it back in. Let's start with the code (that uses xml document that we saw earlier):

   1 // 1: need input factory
   2 SMInputFactory inf = new SMInputFactory(XMLInputFactory.newInstance());
   3 // 2: and root cursor that reads XML document from File:
   4 SMHierarchicCursor rootC = inf.rootElementCursor(new File("empl.xml"));
   5 rootC.advance; // note: 2.0 only method; can also call ".getNext()"
   6 int employeeId = rootC.getAttrIntValue(0);
   7 SMHierarchicCursor nameC = rootC.childElementCursor("name").advance();
   8 SMHierarchicCursor leafC = nameC.childElementCursor().advance();
   9 String first = leafC.collectDescendantText(false);
  10 leafC.advance();
  11 String last = leafC.collectDescendantText(false);
  12 rootC.getStreamReader().closeCompletely()

So how does that work? Here is what is being done and why:

  1. First we create a StaxMate input factory: similar to constructing output factory

  2. Create the root cursor; only traverses over the root element, ignores non-elements like comments
  3. Cursors are initially not positioned over an event, need to advance
  4. Since we know cursor must point to root element, we can access employee id attribute
  5. Need to create a cursor for traversing, filter out all except "name" elements, advance to the first (and only) "name" child element
  6. construct the innermost cursor for traversing immediate children of "name", advance to the first child ("first")
  7. collect all textual content
  8. advance to the second child ("second")
  9. collect all textual content
  10. close the underlying stream reader (important!)

Here are some more things to consider:

Better than Stax 1.0?

Since the original claim was that StaxMate makes things more convenient, let's see what equivalent code for writein would look like, if we didn't have StaxMate:

   1 // 1: need output factory, writer
   2 XMLOutputFactory outf = XMLOutputFactory.newInstance());
   3 FileOutputStream fos = new FileOutputStream(new File("empl.xml"));
   4 XMLStreamWriter xw = outf.createXMLStreamWriter(fos, "UTF-8");
   5 // No way to do automated indentation: must write manually
   6 xw.writeStartDocument(); // not needed with StaxMate
   7 xw.writeComment(" generated: "+new java.util.Date().toString());
   8 xw.writeStartElement("employee");
   9 String idStr = String.valueOf(123);
  10 xw.writeAttribute("id", idStr);
  11 xw.writeCharacters("\n  "); // indent
  12 xw.writeStartElement("name");
  13 xw.writeCharacters("\n    "); // indent
  14 xw.writeStartElement("first");
  15 xw.writeCharacters("Tatu");
  16 xw.writeEndElement(); // for first
  17 xw.writeCharacters("\n    "); // indent
  18 xw.writeStartElement("last");
  19 xw.writeCharacters("Saloranta");
  20 xw.writeEndElement(); // for last
  21 xw.writeCharacters("\n  "); // indent
  22 xw.writeEndElement(); // for name
  23 xw.writeCharacters("\n"); // indent
  24 xw.writeEndElement(); // for employee
  25 xw.writeEndDocument();
  26 xw.close(); // as per Stax 1.0, won't close stream!
  27 fos.close(); // so we need this too

So what does this tell us?

Similarly we could show the alternative for reading XML content: but unfortunately that code would be even more verbose. So to keep this tutorial brief, we'll leave that exercise to readers.

Reading XML content, part 2

Let's have a look at another example, with bit different structure:

  <desc>Longer description</desc>

Assuming we wanted to map this to a simple Data object, we could use:

   1 SMInputFactory inf = new SMInputFactory(XMLInputFactory.newInstance());
   2 SMHierarchicCursor rootC = inf.rootElementCursor(new File("data.xml")).advance();
   3 SMHierarchicCursor valueC = rootC.childElementCursor();
   5 int id = 0;
   6 String name = null, desc = null;
   7 while (valueC.getNext() != null) { // points to START_ELEMENT, null when no more
   8   String elem = valueC.getLocalName();
   9   if ("id".equals(elem)) {
  10     id = elem.getElemIntValue();
  11   } else if ("name".equals(elem)) {
  12     name = elem.getElemStringValue();
  13   } else if ("desc".equals(elem)) {
  14     desc = elem.getElemStringValue();
  15   } else {
  16     throw new IllegalArgumentException("Unexpected element '"+elem+"'");
  17   }
  18 }
  19 rootC.getStreamReader().closeCompletely();
  20 return new Data(id, name, desc);

Advanced Use Cases

Here are links to some use cases that show more advanced usage:


StaxMateTutorial (last edited 2013-02-28 21:35:34 by TatuSaloranta)

Copyright ©2009 FasterXML, LLC