質問
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」を 2 回出力します)。実際には、
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
, 、何か他のものではないでしょうか?
所属していません StackOverflow