The example of this article for you to share the Java parsing/reading XML file method for your reference, the specific contents are as follows
XML file
<?xml version= "1.0"?>
<students>
<student>
<name>John</name>
< grade>b</grade>
<age>12</age>
</student>
<student>
<name >Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18 </age>
</student>
</students>
Java Code:
Package net.viralpatel.java.xmlparser;
Import Java.io.File;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList; public class Xmlparser {public void Getallusernames (String fileName) {try {documentbuilderfactory
DBF = Documentbuilderfactory.newinstance ();
Documentbuilder db = Dbf.newdocumentbuilder ();
File File = new file (fileName);
if (file.exists ()) {Document doc = db.parse (file);
Element Docele = Doc.getdocumentelement (); Print root element of the document SYSTEM.OUT.PRINTLN ("root element of the document:" + Docele.)
Getnodename ());
NodeList studentlist = docele.getelementsbytagname ("student"); Print total student elements in document System.out. println ("Total Students:" + studentlist.getlength ()); if (studentlist!= null && studentlist.getlength () > 0) {for (int i = 0; i < Studentlist.getlen Gth ();
i++) {Node node = Studentlist.item (i); if (node.getnodetype () = = Node.element_node) {System.out. println ("===============
======");
Element e = (element) node;
NodeList nodelist = e.getelementsbytagname ("name"); System.out.println ("Name:" + nodelist.item (0). Getchildnodes (). Item (0). GetNode
Value ());
NodeList = E.getelementsbytagname ("Grade"); System.out.println ("Grade:" + nodelist.item (0). Getchildnodes (). Item (0). Getnod
Evalue ());
NodeList = E.getelementsbytagname ("Age"); System.out.println ("Age:" + NodelIst.item (0). Getchildnodes (). Item (0). Getnodevalue ());
}} else {system.exit (1);
catch (Exception e) {System.out.println (e);
} public static void Main (string[] args) {xmlparser parser = new Xmlparser ();
Parser.getallusernames ("C:\\test.xml"); }
}
The above is the entire content of this article, I hope to help you learn.