【发布时间】:2015-11-13 01:59:52
【问题描述】:
我们正在尝试使用 SAX Parser 解析 XML。 我们的环境: Java 版本:1.7
<wrappercell borderWidth="0.9f" border="NO_BORDER" colSpan="1">
<phrase font="BOLD_ARIAL">
<token>1234</token>
</phrase>
</wrappercell>
在我们的 startElement 中,我们正在执行以下操作
public void startElement(String uri, String localName, String qName, Attributes attributes){
if("wrappercell".equals(qName)){
elemenstack.push(attributes);
}else if("phrase".equals(qName)){
elemenstack.push(attributes);
}
}
在我们的 EndElement 中,我们想引用我们在 startelement 期间推送的属性
public void endElement(String uri, String localName, String qName) throws SAXException {
if("wrappercell".equals(qName)){
System.out.println(((Attributes)elemenstack.pop()).getLength());
}else if("phrase".equals(qName)){
System.out.println(((Attributes)elemenstack.pop()).getLength());
}
}
这对于 getLength() 总是返回零。我们引用另一个Ques,它说属性对象在每个起始元素处具有相同的实例。
除了下面我们尝试过的选项之外,是否还有其他选项可以引用 endelement 中的 startelement 值;
我们的解决方案计划
public void startElement(String uri, String localName, String qName, Attributes attributes){
if("wrappercell".equals(qName)){
elementAttribute.put(attribute.getQName(1),attributes.getValue(1));
elemenstack.push(elementAttribute);
}else if("phrase".equals(qName)){
elementAttribute.put(attribute.getQName(1),attributes.getValue(1));
elemenstack.push(elementAttribute);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if("wrappercell".equals(qName)){
System.out.println(((HashMap<String,String>)elemenstack.pop()).size());
}else if("phrase".equals(qName)){
System.out.println(((HashMap<String,String>)elemenstack.pop()).size());
}
}
【问题讨论】:
-
elementAttribute来自哪里?你似乎在分享它。您需要分配一个新实例以推送到您的堆栈中。 -
我们正在创建一个名为 elementattribute 的 hashmap,以便我们可以访问 startelement 和 end element 之间的值。它按预期工作。但是我们想有没有其他方法可以解决这个问题?
标签: java xml-parsing attributes itext sax