-1
我正在解析XML文件(源代码)并同时写入新文件(结果)。解析XML时ArrayIndexOutOfBoundsException异常
这里的源XML:
<?xml version="1.0"?>
<poll>
<pollHead>
<code>1</code>
<title>Here's the title</title>
<description>Desc</description>
<author>Hilbert Von Neumann</author>
<date>2013-09-15T11:53:00</date>
</pollHead>
<pollBody>
<topic code="T1">
<topicHead>
<title>Topic title bla</title>
<description>description bla bla</description>
</topicHead>
<topicBody>
<question code="T1Q1" type="unique">How do you blabla?</question>
<option code="T1Q1_1">bla bla</option>
<option code="T1Q1_2">ok bla</option>
<option code="T1Q1_3">strabla</option>
<question code="T1Q2" type="unique">Are they bli bli?</question>
<option code="T1Q2_1">Lorem Ipsum</option>
<option code="T1Q2_2">Lorem Ipsum2</option>
<option code="T1Q2_3">Lorem Ipsum3</option>
</topicBody>
</topic>
</pollBody>
</poll>
我要分析此源XML代码,写一个新的XML转换中<answer>
元素<option>
元素。但是结果xml应该只列出answer
元素,它们具有code
属性,其值包含在特定的HashMap中。因此,如果<option>
已获得包含在我的HashMap中的代码,则<option>
将变为<answer>
,否则应该将其删除(不写入结果xml中)。 N.B .: HashMap在下面的代码中被称为questionAnswers
我已经写了这段代码,但它给了我一个ArrayIndexOutOfBoundsException。下面的代码:
while (xer.hasNext()) {
XMLEvent event = xer.nextEvent();
if (event.getEventType() == XMLEvent.START_ELEMENT && event.asStartElement().getName().getLocalPart().equals("option")) {
Iterator ite = event.asStartElement().getAttributes();
while (ite.hasNext()) {
Attribute attr = (Attribute) ite.next();
if (attr.getName().getLocalPart().equals("code") && questionAnswers.containsValue(attr.getValue())) {
String optionCodeValue = attr.getValue();
writer.add(eventFactory.createStartElement("", null, "answer"));
writer.add(eventFactory.createAttribute("code", optionCodeValue));
}
}
event = xer.nextEvent();
} else {
writer.add(event);
}
}
writer.close();
而这里的错误:
javax.xml.stream.XMLStreamException: No element was found to write: java.lang.ArrayIndexOutOfBoundsException: -1
at com.sun.xml.internal.stream.writers.XMLStreamWriterImpl.writeEndElement(XMLStreamWriterImpl.java:930)
at com.sun.xml.internal.stream.writers.XMLEventWriterImpl.add(XMLEventWriterImpl.java:186)
...
缺少什么我在这里?怎么了?
真棒答案,我很高兴你这样的发现了一个用户。非常好,谢谢:) –
谢谢。很高兴帮助。 –