JAVA - 如何绕过没有打开标记的封闭XML标记

问题描述 投票:0回答:2

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

谢谢。

java arrays xml string dom
2个回答
0
投票

你使用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("\\/");
}

0
投票

在示例xml中:

<deviceInfo>
    <device>TV2345</device>
    <deviceType>Television</deviceType>
    <location />
    <size />
</deviceInfo>

没有deviceId标签,但你想从NodeList获得第一件商品:

eElement.getElementsByTagName("deviceId").item(0);

这个操作失败了java.lang.ArrayIndexOutOfBoundsException

© www.soinside.com 2019 - 2024. All rights reserved.