我正在尝试使用 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 的属性列表的大小为零。为什么?我怎样才能克服这个问题?

编辑:

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();

评估为零。

谢谢

有帮助吗?

解决方案

我已经有了一个完整的例子从工作有并适应它为您的文件:

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>

其他提示

Attributes.getValue() 并不像看上去那么简单。这 javadoc 说:

通过XML合格(前缀)名称查找属性的值。

因此,如果存在任何名称空间复杂性,仅传递“initialstate”可能不起作用,因为“initialstate”在技术上不是限定名称。

我建议尝试一下其他方法 Attributes 类,例如 getValue(int), ,您可能会取得更大的成功。


编辑: :另一种可能性是,调用 startElement 并不是指您认为的元素。您是否已验证 localName 论点确实是 scxml, ,而不是其他东西?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top