Java SAX 解析器,存储属性
我试图将当前文档位置存储在堆栈中,按下 startElement,弹出 endElement。现在我正在使用:
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));
....
不幸的是,当它稍后尝试读取 atts 时,它会给出错误: 引起原因:java.lang.IllegalStateException:属性只能在startElement()的范围内使用。
有没有快速、可靠的方法来存储属性? 另外,有没有比为每个开始标签构造一个新的自定义对象 StackElement 更好的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将属性推送到自定义对象堆栈时,您将获取实际的属性对象,根据 文档说this:
atts - 附加到元素的属性。如果没有属性,则它应该是一个空的 Attributes 对象。 startElement 返回后该对象的值未定义(强调我的)
您应该在 startElement(...) 方法中捕获 Map中的属性。这样您就可以在任何您想要的地方使用它们。
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.
如果
Attributes
是上下文相关的,请在StackElement
构造函数中从它们中提取所需的内容(并且不存储引用)。像这样的事情会做:
ps 看起来我抄袭了@nicholas的答案,但老实说,当他发布时我已经把它打出来并且正在编写代码。
If
Attributes
is context sensitive, extract what you need from them in theStackElement
constructor (and don't store the reference).Something like this would do:
p.s. It might seem like I plagiarised @nicholas's answer, but honestly, I had already typed it out and was working on the code when he posted.