JAVA - 如何在没有开放标记的情况下绕过已关闭的 XML 标记

我正在读取以下 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("\\/");        

}

谢谢。


冉冉说
浏览 107回答 2
2回答

达令说

使用返回对象的方法。如果没有具有给定名称的元素,则返回 。因此,下面的代码可以安全地获取文本内容:getElementsByTagNameorg.w3c.dom.NodeListNodeList.getLength0NodeList locations = document.getElementsByTagName("location");if (locations.getLength() > 0) {&nbsp; &nbsp; String textContent = locations.item(0).getTextContent();&nbsp; &nbsp; System.out.println(textContent);}或者你可以创建方法来完成它:public static String getFirstTextContent(Document node, String tagName) {&nbsp; &nbsp; NodeList locations = node.getElementsByTagName(tagName);&nbsp; &nbsp; if (locations.getLength() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; return locations.item(0).getTextContent();&nbsp; &nbsp; }&nbsp; &nbsp; return "";}你的代码可能看起来像这样:String locationNode = getFirstTextContent(document, "location");if (locationNode.length() > 0) {&nbsp; &nbsp; String DEVICEID = getFirstTextContent(document, "deviceId");&nbsp; &nbsp; String[] LOCATION = getFirstTextContent(document, "location").split("\\/");}

暮色呼如

在示例 xml 中:<deviceInfo>&nbsp; &nbsp; <device>TV2345</device>&nbsp; &nbsp; <deviceType>Television</deviceType>&nbsp; &nbsp; <location />&nbsp; &nbsp; <size /></deviceInfo>没有标记,但您正在尝试从 中获取第一项:deviceIdNodeListeElement.getElementsByTagName("deviceId").item(0);并且此操作失败java.lang.ArrayIndexOutOfBoundsException
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java