I’m trying to store the current document position in a stack, pushing on startElement, popping on endElement. Right now I’m using:
public void startElement(String namespaceURI, String elname,
String qName, Attributes atts) throws SAXException {
original.append(innerText);
original.append("<");
original.append(elname);
original.append(">");
docStack.push(new StackElement(elname,atts));
....
Unfortunately when it tries to read the atts later, it gives error:
Caused by: java.lang.IllegalStateException: Attributes can only be used within the scope of startElement().
Is there any fast, reliable way to store the attributes?
Also, is there a better way to do this than constructing a new custom object StackElement for each start tag?
When you push the Attributes onto your custom object stack, you are taking the actual Attributes object, which, according to the documentation says this:
atts – the attributes attached to the element. If there are no attributes, it shall be an empty Attributes object. The value of this object after startElement returns is undefined (emphasis mine)
You should instead, in your startElement(…) method capture the attributes in a Map<String,String>. This way you can use them where ever you want to.