无法使用SAX读取某些属性 [英] Can't read some attributes with SAX
本文介绍了无法使用SAX读取某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用SAX解析该文档:
I'm trying to parse that document with SAX:
<scxml version="1.0" initialstate="start" name="calc">
<datamodel>
<data id="expr" expr="0" />
<data id="res" expr="0" />
</datamodel>
<state id="start">
<transition event="OPER" target="opEntered" />
<transition event="DIGIT" target="operand" />
</state>
<state id="operand">
<transition event="OPER" target="opEntered" />
<transition event="DIGIT" />
</state>
</scxml>
我很好地阅读了所有属性,除了initialstate和name...
我使用startElement处理程序获取属性,但scxml的属性列表的大小为零。为什么?我如何克服这个问题?
I read all the attributes well, except "initialstate" and "name"... I get the attributes with the startElement handler, but the size of the attribute list for scxml is zero. Why? How I can overcome that problem?
编辑:
public void startElement(String uri, String localName, String qName, Attributes attributes){
System.out.println(attributes.getValue("initialstate"));
System.out.println(attributes.getValue("name"));
}
解析第一个标签时不起作用(打印null 两次)。事实上,
that, when parsing the first tag, doesn't work (prints "null" two times). In fact,
attributes.getLength();
评估为零。
谢谢
推荐答案
我有一个完整的例子来自那里并根据你的文件调整它:
I've got a full example working from there and adapted it for your file:
public class SaxParserMain {
/**
* @param args
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
CustomHandler handler = new CustomHandler();
parser.parse(new File("file/scxml.xml"), handler);
}
}
和
public class CustomHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
System.out.println();
System.out.print("<" + qName + "");
if (attributes.getLength() == 0) {
System.out.print(">");
} else {
System.out.print(" ");
for (int index = 0; index < attributes.getLength(); index++) {
System.out.print(attributes.getLocalName(index) + " => "
+ attributes.getValue(index));
}
System.out.print(">");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.print("\n</" + qName + ">");
}
}
输出为:
<scxml version => 1.0initialstate => startname => calc>
<datamodel>
<data id => exprexpr => 0>
</data>
<data id => resexpr => 0>
</data>
</datamodel>
<state id => start>
<transition event => OPERtarget => opEntered>
</transition>
<transition event => DIGITtarget => operand>
</transition>
</state>
<state id => operand>
<transition event => OPERtarget => opEntered>
</transition>
<transition event => DIGIT>
</transition>
</state>
</scxml>
这篇关于无法使用SAX读取某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文