[Java Xml] Đếm tổng số Xml Element trong Document bằng DOM Parser

Trong bài viết này, chúng ta sẽ cùng tìm hiểu về cách sử dụng DOM Parser để đếm tổng số element trong file XML. Đầu tiên, tìm kiếm element bằng tên và sau đó có thể sử dụng NodeList.getLength() để có được tổng số phần tử.

Java:
    NodeList list = doc.getElementsByTagName("staff");
    System.out.println("Total of elements : " + list.getLength());
File : file.xml
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <staff id="1">
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>2000000</salary>
        <age>29</age>
    </staff>
    <staff id="2">
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>1000000</salary>
    </staff>
    <staff id="3">
        <firstname>Ali</firstname>
        <lastname>Baba</lastname>
        <nickname>Alibaba</nickname>
        <salary>199000</salary>
        <age>40</age>
    </staff>
</company>

File : CountXMLElement.java – Tìm số lượng “staff” elements.
Java:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CountXMLElement {

  public static void main(String argv[]) {

    try {
        String filepath = "c:\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        NodeList list = doc.getElementsByTagName("staff");

        System.out.println("Total of elements : " + list.getLength());

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
  }
}
Kết quả
Code:
Total of elements : 3

Cám ơn các bạn đã theo dõi. Hẹn gặp lại các bạn trong các bài viết sau :)

Bài viết tham khảo tại:https://mkyong.com/java/how-to-count-xml-elements-in-java-dom-parser
 

Bình luận

Joe

Thành viên VIP
21/1/13
2,898
1,293
113
SAX and DOM are useful when one has to work with the elements and attributes of a large & complex XML file. You have showed CDJ a lot of ways how to work with STREAM in conjunction with List and Array. For a simple XML file as it is in your example "file.xml" the simplest way is to work with Stream. Simplicity is the key to success.
PHP:
import java.io.File;
import java.util.Arrays;
import java.nio.file.Files;
// Joe Nartca (C)
public class CountXMLNodes {

  public static void main(String argv[]) throws Exception {
      long cnt = Arrays.stream(new String(Files.readAllBytes((new File(argv[0])).toPath()))
                       .replace("< ", "<").replace("/ ", "/").replace(" >", ">")
                       .split("</"+argv[1]+">"))
                       .filter(s -> s.indexOf(argv[1]) >= 0)
                       .count();
    System.out.println(cnt+" "+argv[1]);
  }
}
and the output
Code:
C:\links\java\DOM>javac -g:none -d ./classes CountXMLNodes.java

C:\links\java\DOM>java CountXMLNodes file.xml staff
3 staff

C:\links\java\DOM>
 
Sửa lần cuối:
  • Like
Reactions: quydtkt

quydtkt

Administrator
1/11/19
319
30
28
26
I have had many articles about Java 8 Stream. However I don't think it is possible to use it in this case. Very interesting :))
 
  • Like
Reactions: Joe

Joe

Thành viên VIP
21/1/13
2,898
1,293
113
Next time, when I get some spare time I'll show you and CongdongJava how to develop DOM/SAX using STREAM-LIST-ARRAY and how to I18N with XML. Do you know what I18N is ? The first letter I and 18 letters in-between, the last letter is N. Together I18N stands for
I N T E R N A T I O N A L I Z A T I O N
 
Sửa lần cuối: