JAVA 忽略注释掉的 xml 标签
JAVA Ignore commented out xml tags
当我解析一个 XML 文档时,我得到注释掉的代码作为一个节点(一开始这不是个好主意),我不想知道我们什么时候注释掉 node/bulk 而不是解析它。
这是解析 XML 元素的代码:
private static boolean updateXML(File file, Document doc, NodeList nodeList)
{
if(nodeList==null)
return false;
boolean somethingChanged = false;
for(int i=0;i<nodeList.getLength();i++)
{
if(nodeList.item(i).hasChildNodes())
{
somethingChanged |= updateXML(file, doc, nodeList.item(i).getChildNodes());
}
else
{ ... }
}
}
当我调试它时,我可以看到注释掉的部分作为一个完整的节点出现。
如何忽略这些评论?
使用这个:
Node node = nodeList.item(i);
if(node.getNodeType() == Node.COMMENT_NODE) {
continue;
} else {
//do something
}
使用DocumentBuilderFactory
可以设置完全忽略文件中的注释。
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setIgnoringComments(true);
现在解析任何文件:
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filePath);
文档将不包含任何评论。
当我解析一个 XML 文档时,我得到注释掉的代码作为一个节点(一开始这不是个好主意),我不想知道我们什么时候注释掉 node/bulk 而不是解析它。
这是解析 XML 元素的代码:
private static boolean updateXML(File file, Document doc, NodeList nodeList)
{
if(nodeList==null)
return false;
boolean somethingChanged = false;
for(int i=0;i<nodeList.getLength();i++)
{
if(nodeList.item(i).hasChildNodes())
{
somethingChanged |= updateXML(file, doc, nodeList.item(i).getChildNodes());
}
else
{ ... }
}
}
当我调试它时,我可以看到注释掉的部分作为一个完整的节点出现。
如何忽略这些评论?
使用这个:
Node node = nodeList.item(i);
if(node.getNodeType() == Node.COMMENT_NODE) {
continue;
} else {
//do something
}
使用DocumentBuilderFactory
可以设置完全忽略文件中的注释。
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setIgnoringComments(true);
现在解析任何文件:
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filePath);
文档将不包含任何评论。