gpt4 book ai didi

java - 使用 node.getTextContent() 从 xml 获取值时无法删除空格

转载 作者:行者123 更新时间:2023-12-01 19:44:37 29 4
gpt4 key购买 nike

我有使用 DOM 解析器解析的 xml 配置文件。当我使用 node.getTextContent(); 从子节点获取值时,我无法删除字符串 value 中的空格。当我给出没有空格的值时,它会起作用。但是,我也必须处理负面场景。

我尝试了trim()、replaceAll("\s", "") 和replaceAll("\u00A0", "");但没有任何效果

 NodeList serviceAddrNodeList=serviceAddressesNode.getChildNodes();

packetSendingIplist =new ArrayList();

for (int l = 0; l < serviceAddrNodeList.getLength(); l++) {

Node serviceAddrNode=serviceAddrNodeList.item(l);

if(serviceAddrNode.getNodeType()==Node.ELEMENT_NODE){

String packetSendingIp = serviceAddrNode.getTextContent();
packetSendingIp.trim(); //replaceAll("\s", "") and replaceAll("\u00A0", "")
if(checkValidIp(packetSendingIp)){

log("invalid service_addr-"+packetSendingIp+"ignoring this
listening point ");
}
}
}

xml:

  <service_addresses>
<!-- host1 -->
<service_addr>172.17.1.16 </service_addr>
<service_addr>172.17.1.17 </service_addr>
<!-- host12-->
<service_addr>172.17.1.32</service_addr>//works becuase no space here
<service_addr>172.17.1.33 </service_addr>
</service_addresses>

最佳答案

试试这个

File fXmlFile = new File("your xml file path");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList nodeList = doc.getElementsByTagName("service_addr");
for(int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getTextContent().trim());
}

输出,没有任何空格

172.17.1.16
172.17.1.17
172.17.1.32
172.17.1.33

关于java - 使用 node.getTextContent() 从 xml 获取值时无法删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886491/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com