Gambardella, ...">

SAX analysis - an effective way to get text nodes

Given this piece of XML

<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> 

In SAX, it is easy to get attribute values:

 @Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException{ if(qName.equals("book")){ String bookId = attributes.getValue("id"); ... } } 

But to get the value of the text node, for example. <author> tag value, it's pretty complicated ...

 private StringBuffer curCharValue = new StringBuffer(1024); @Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("author")){ curCharValue.clear(); } } @Override public void characters (char ch[], int start, int length) throws SAXException { //already synchronized curCharValue.append(char, start, length); } @Override public void endElement (String uri, String localName, String qName) throws SAXException { if(qName.equals("author")){ String author = curCharValue.toString(); } } 
  • I'm not sure if the above example even works, what do you think of this approach?
  • Is there a better way? (to get the text node)
+7
java xml sax
source share
2 answers

This is the usual way to do this with SAX.

Just be careful that characters() can be called more than once per tag. For more information, see question . Here is a complete example .

Otherwise, you can try StAX .

+8
source share
 public void startElement(String strNamespaceURI, String strLocalName, String strQName, Attributes al) throws SAXException { if(strLocalName.equalsIgnoreCase("HIT")) { String output1 = al.getValue("NAME"); //this will work but how can we parse if NAME="abc" only ? } } 
+1
source share

All Articles