为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2022-08-17 10:46:44
我正在读取以下 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("\\/");        }谢谢。
查看完整描述

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("\\/");

}


查看完整回答
反对 回复 2022-08-17
?
暮色呼如

TA贡献1853条经验 获得超9个赞

在示例 xml 中:


<deviceInfo>

    <device>TV2345</device>

    <deviceType>Television</deviceType>

    <location />

    <size />

</deviceInfo>

没有标记,但您正在尝试从 中获取第一项:deviceIdNodeList


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

并且此操作失败java.lang.ArrayIndexOutOfBoundsException


查看完整回答
反对 回复 2022-08-17
  • 2 回答
  • 0 关注
  • 106 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号