4

我正在尝试使用 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();

评估为零。

谢谢

4

2 回答 2

3

我从那里得到了一个完整的例子,并为您的文件进行了调整:

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>
于 2010-01-13T11:58:09.593 回答
1

Attributes.getValue()并不像看起来那么简单。javadoc说:

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

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

我建议在Attributes课堂上尝试使用其他方法,例如getValue(int),您可能会在这些方法中获得更多成功。


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

于 2010-01-13T11:44:40.493 回答