次のXMLコードがあります
<class name="ContentStreamer">
<method name="sendAudio">
<criteria>medium</criteria>
</method>
<method name="sendVideo">
<criteria>weak</criteria>
</method>
</class>
次のコードで繰り返し処理します (XMLStreamReader を使用)
if (reader.getEventType() == XMLStreamReader.START_ELEMENT) {
String elementName = reader.getName().toString();
if (elementName.equalsIgnoreCase("class")) {
// get the class name and construct a Class
classComposition = new ClassComposition();
classComposition.setName(reader.getAttributeValue(0));
System.out.println("***** Class: " + reader.getAttributeValue(0));
}
else if (elementName.equalsIgnoreCase("method")) {
MethodCriterion method = new MethodCriterion();
method.setMethodName(reader.getAttributeValue(0));
System.out.println("***** Method: " + reader.getAttributeValue(0));
// move forward and get the text from the '<criteria>' element
reader.next();
System.out.println("!!!" + reader.getName().toString());
}
else if (elementName.equalsIgnoreCase("criterion")) {
return compositions;
}
}
コンソールに表示される出力は次のとおりです。
***** Class: ContentStreamer
***** Method: sendAudio
There was an error parsing the composition file
java.lang.IllegalStateException: Illegal to call getName() when event type is CHARACTERS. Valid states are START_ELEMENT, END_ELEMENT
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getName(Unknown Source)
問題を起こしているコードの領域は、最後の ' reader.next()
' と ' System.out.println
' です。「」要素はテキスト要素のみであり、API は、このメソッドが「テキストのみの要素」(引用) のテキストを読み取ることを示しているため、「 reader.getName().toString()
」を「 」に置き換えました。「 」を使用してイベント タイプを確認したところ、「CHARACTERS」に対応する 4 が返されました。その場合、「」を試してみましたが、これは空の文字列を返します。私はJava 6を使用しています。ここで何が起こっているのでしょうか?reader.getElementText()
<criteria>
reader.getEventType()
reader.getText()