Search code examples
javaxmlextractstax

stax - get xml node as string


xml looks like so:

<statements>
   <statement account="123">
      ...stuff...
   </statement>
   <statement account="456">
      ...stuff...
   </statement>
</statements>

I'm using stax to process one "<statement>" at a time and I got that working. I need to get that entire statement node as a string so I can create "123.xml" and "456.xml" or maybe even load it into a database table indexed by account.

using this approach: http://www.devx.com/Java/Article/30298/1954

I'm looking to do something like this:

String statementXml = staxXmlReader.getNodeByName("statement");

//load statementXml into database

Solution

  • Why not just use xpath for this?

    You could have a fairly simple xpath to get all 'statement' nodes.

    Like so:

    //statement
    

    EDIT #1: If possible, take a look at dom4j. You could read the String and get all 'statement' nodes fairly simply.

    EDIT #2: Using dom4j, this is how you would do it: (from their cookbook)

    String text = "your xml here";
    Document document = DocumentHelper.parseText(text);
    
    public void bar(Document document) {
       List list = document.selectNodes( "//statement" );
       // loop through node data
    }