2 回答
TA贡献1821条经验 获得超6个赞
使用返回对象的方法。如果没有具有给定名称的元素,则返回 。因此,下面的代码可以安全地获取文本内容:getElementsByTagNameorg.w3c.dom.NodeListNodeList.getLength0
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("\\/");
}
TA贡献1853条经验 获得超9个赞
在示例 xml 中:
<deviceInfo>
<device>TV2345</device>
<deviceType>Television</deviceType>
<location />
<size />
</deviceInfo>
没有标记,但您正在尝试从 中获取第一项:deviceIdNodeList
eElement.getElementsByTagName("deviceId").item(0);
并且此操作失败java.lang.ArrayIndexOutOfBoundsException
添加回答
举报
