我试图仅获取所有elemnt类型的节点,然后要执行一些特定的操作,但是在ELEMENT_NODE的情况下,node.getNodeType不能按预期工作-如果阻塞所有子节点,它将进入
示例xml-
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.002.001.05">
<CstmrPmtStsRpt>
<GrpHdr>
<MsgId>00990119071512383635</MsgId>
<CreDtTm>2019-07-15T12:38:36.304+05:30</CreDtTm>
<InitgPty>
<Nm>appSend</Nm>
</InitgPty>
</GrpHdr>
....
这是我的代码-我想为诸如 MsgId 之类的元素做某事,为 GrpHdr 我想做一些不同的操作
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setValidating(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(fileName));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
node.normalize();
if( node.getNodeType() == Node.ELEMENT_NODE ){
// do operation for only elements
}else{
// do other operation for non elements
}
}
}catch (Exception e){
}
有人遇到过类似的问题
提前谢谢
答案 0 :(得分:0)
好吧,以下不是一个好的解决方法-但这就是我解决的方法
元素-总是只有一个孩子。
所以我用下面的代码对其进行了调整-
if( node.getChildNodes().getLength() != 1 ){
// do operation for only non - elements
}else{
// do other operation for elements
}
我想这只是一个解决方法,不是一个好的解决方案