我正在阅读以下XML文件:
在某些时候,我发现标签已关闭但未打开像位置和大小。我的逻辑是将这些标签读入一个数组,并在某些时候用一个失败
java.lang.ArrayIndexOutOfBoundsException
<deviceInfo>
<device>TV2345</device>
<deviceType>Television</deviceType>
<location/>
<size/>
</deviceInfo>
这是我的代码阅读它并试图逃避它,但它不起作用:
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String LocationNode=eElement.getElementsByTagName("location").item(0).getTextContent();
if (LocationNode.length() > 0) {
String DEVICEID = eElement.getElementsByTagName("deviceId").item(0).getTextContent();
String[] LOCATION = eElement.getElementsByTagName("location").item(0).getTextContent().split("\\/");
}
谢谢。
你使用getElementsByTagName
方法返回org.w3c.dom.NodeList
对象。如果没有给定名称的元素NodeList.getLength
方法返回0
。因此,下面的代码安全地获取文本内容:
NodeList locations = document.getElementsByTagName("location");
if (locations.getLength() > 0) {
String textContent = locations.item(0).getTextContent();
System.out.println(textContent);
}
或者您可以创建将执行此操作的方法:
public static String getFirstTextContent(Document node, String tagName) {
NodeList locations = node.getElementsByTagName(tagName);
if (locations.getLength() > 0) {
return locations.item(0).getTextContent();
}
return "";
}
你的代码看起来像这样:
String locationNode = getFirstTextContent(document, "location");
if (locationNode.length() > 0) {
String DEVICEID = getFirstTextContent(document, "deviceId");
String[] LOCATION = getFirstTextContent(document, "location").split("\\/");
}
在示例xml中:
<deviceInfo>
<device>TV2345</device>
<deviceType>Television</deviceType>
<location />
<size />
</deviceInfo>
没有deviceId
标签,但你想从NodeList
获得第一件商品:
eElement.getElementsByTagName("deviceId").item(0);
这个操作失败了java.lang.ArrayIndexOutOfBoundsException