【问题标题】:total number of nodes in xmlxml中的节点总数
【发布时间】:2018-11-30 16:43:48
【问题描述】:

我需要获取 xml 文件中的节点总数 对于我们使用的元素
NodeList nodeList = doc.getElementsByTagName("*"); 但是对于节点,如果您有任何想法 谢谢你

【问题讨论】:

  • 最好更明确地说明您要计算哪些节点。属性?命名空间?空白文本节点?实体和 CDATA 节点?

标签: java xml dom


【解决方案1】:

下面的代码可能会起作用。 这个想法是使用递归来计算 XML 文件的每个元素(以及它的子元素)。

public class Main {

    int totalNodes = 0;

    public Main() throws Exception {
        String file = getClass().getResource("/test.xml").getFile();
        File fXmlFile = new File(file);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        countNodes(doc.getDocumentElement());
        System.out.println(totalNodes);
    }

    public void countNodes(Node node) {
        System.out.println(node.getNodeName());
        totalNodes++;
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {                    
                countNodes(currentNode);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }
}

【讨论】:

  • 这不计算属性节点。这可能是也可能不是预期的结果。
  • 你的代码相当于这个函数:int N = doc.getElementsByTagName("*").getLength()
  • @MichaelKay ,稍微改变一下代码可能适用于其他类型的节点,例如属性节点。在 if 子句中使用 Node.ATTRIBUTE_NODE 可能会如您所愿。
  • @ThiagoProcaci 我没有任何期望。我只是指出要求不明确,在这种情况下,最好在明确之前不要编写任何代码。
猜你喜欢
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多