我正在尝试使用 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 属性列表的大小为零。为什么?我怎样才能克服这个问题?
Edit:
public void startElement(String uri, String localName, String qName, Attributes attributes){
System.out.println(attributes.getValue("initialstate"));
System.out.println(attributes.getValue("name"));
}
当解析第一个标签时,它不起作用(打印“null”两次)。实际上,
attributes.getLength();
评估为零。
Thanks
我有一个完整的示例there http://www.javabeat.net/tips/23-parsing-xml-documents-using-sax.html并根据您的文件进行调整:
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);
}
}
and
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)