I have the following XML code
<class name="ContentStreamer">
<method name="sendAudio">
<criteria>medium</criteria>
</method>
<method name="sendVideo">
<criteria>weak</criteria>
</method>
</class>
I iterate over it with the following code (using 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;
}
}
The output I get on the console is:
***** 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)
The area of the code that is giving me trouble is the last 'reader.next()
' and 'System.out.println
'.
I have replaced the 'reader.getName().toString()
' with 'reader.getElementText()
' as the '<criteria>
' element is a text element only and the API says that this methods reads the text of a 'text-only element' (to quote). I have checked the event type using 'reader.getEventType()
' and it returns a 4, which corresponds to开发者_如何转开发 'CHARACTERS'. So in that case, I tried 'reader.getText()
' and this just returns an empty string. I'm using Java 6. Any ideas what's going on here?
Between <method name="sendAudio">
and <criteria>medium</criteria>
, you have a newline char and a number of spaces. These form a text node, and that's why you get CHARACTERS
as the event type.
I'm surprised you got an empty string when calling getText()
. Are you sure it wasn't a string with only a newline and space characters?
精彩评论