我有一个使用DOM解析器解析的xml配置文件。当我使用node.getTextContent()从子节点获取值时,我无法删除字符串值中的空格。当我给不带空格的值时,它可以工作。但是,我也必须处理负面的场景。
我尝试过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>
答案 0 :(得分:1)
您可以通过正则表达式删除内容开头和结尾的所有空格:
public class Main {
public static final String DEST = "html_1.pdf";
private static final String WHITESPACE_REGEX = "(^( )*|( )*$)";
public static void main(String[] args) throws Exception {
Assert.assertEquals(" 192.168.1.1 ".replaceAll(WHITESPACE_REGEX, StringUtils.EMPTY), "192.168.1.1");
Assert.assertEquals(" 192.168.1.1 ".replaceAll(WHITESPACE_REGEX, StringUtils.EMPTY), "192.168.1.1");
Assert.assertEquals("192.168.1.1 ".replaceAll(WHITESPACE_REGEX, StringUtils.EMPTY), "192.168.1.1");
Assert.assertEquals("192.168.1.1".replaceAll(WHITESPACE_REGEX, StringUtils.EMPTY), "192.168.1.1");
}
}
答案 1 :(得分:1)
尝试
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
答案 2 :(得分:1)
您不能那样做Trim()。您必须再次将此输出分配给变量,因为在执行此操作后,它仍将具有相同的值。在该行上添加修剪,它应能按预期工作。
String packetSendingIp = serviceAddrNode.getTextContent().trim()