在解析XMl时,如果XML有一个父标记,那么它工作正常,如果它有多个父标记,那么它会抛出以下异常。
java.lang.IllegalStateException: Current state END_ELEMENT is not among the statesCHARACTERS, COMMENT, CDATA, SPACE, ENTITY_REFERENCE, DTD valid for getText()
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getText(Unknown Source)
at com.axxonet.queue.xmlParserValues.parse(xmlParserValues.java:37)
at com.axxonet.queue.xmlParserValues.main(xmlParserValues.java:19)
如果XML格式具有这种结构,那么它工作正常。
<Address>
<Name>Rahul</Name>
<ID>2345</ID>
<City>Pune</City>
<Street>Gandhi Nagar</Street>
</Address>
如果any字段值为null,则生成标签<phone/>
然后在解析时我得到以下异常。
<Address>
<Name>Rahul</Name>
<ID>2345</ID>
<City/>
<Street>Gandhi Nagar</Street>
</Address>
我尝试在IllegalStateException
块中添加catch
例外,但它仍在抛出异常。
我的代码如下,
Map<String, String> map = new HashMap<String, String>();
XMLStreamReader xr;
try {
xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("E:/Softwares/eclipse/reqOutputFile.xml"));
while(xr.hasNext()) {
int e = xr.next();
if (e == XMLStreamReader.START_ELEMENT) {
String name = xr.getLocalName();
xr.next();
String value = null;
try{
value = xr.getText();
}
catch(IllegalStateException ex)
{
ex.printStackTrace();
}
map.put(name, value);
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (XMLStreamException e1) {
e1.printStackTrace();
} catch (FactoryConfigurationError e1) {
e1.printStackTrace();
}
我们如何处理异常?
答案 0 :(得分:1)
我认为你的xml应该是这样的
<Root>
<Address>
<Name>Rahul</Name>
<ID>2345</ID>
<City>Pune</City>
<Street>Gandhi Nagar</Street>
</Address>
<ContactAddress>
<phone>223363</phone>
<mobile>9988776655</mobile>
</ContactAddress>
</Root>
答案 1 :(得分:1)
更改代码以执行以下操作以利用getElementText()
方法,而不是尝试前进到可能不存在的文本节点:
int e = xr.next();
if (e == XMLStreamReader.START_ELEMENT) {
String name = xr.getLocalName();
// xr.next();
String value = null;
try{
if(xr.hasText()) {
value = xr.getElementText(); // was xr.getText();
}
}
catch(IllegalStateException ex)
{
ex.printStackTrace();
}
map.put(name, value);
}