This article mainly introduces how to read XML files in Java. if you need it, you can refer to the common problems of CSDN today to understand how to read XML files in Java.
Go directly to the code, and the comments are clearly written!
Import java. io. *; 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 XMLReaderTest {public static void main (String args []) {Element element = null; // you can use absolute path strength File f = new File ("test. xml "); // documentBuilder cannot be directly instantiated for abstraction (converting an XML file to a DOM file) DocumentBuilder db = null; DocumentBuilderFactory dbf = null; try {// return the documentBuilderFactory object dbf = DocumentBuilderFactory. newInstance (); // return the database object. use the documentBuilderFatory object to obtain the returned documentBuildr object db = dbf. newDocumentBuilder (); // Get a DOM and return it to the document object Document dt = db. parse (f); // Get an elment root element = dt. getDocumentElement (); // Obtain the root node System. out. println ("root element:" + element. getNodeName (); // Obtain the subnode NodeList childNodes = element under the root element. getChildNodes (); // traverse these subnodes for (int I = 0; I <childNodes. getLength (); I ++) {// Obtain the Node node1 = childNodes for each position I. item (I); if ("Account ". equals (node1.getNodeName () {// if the node name is "Account", the Account element attribute type System is output. out. println ("\ r \ n find an account. region: "+ node1.getAttributes (). getNamedItem ("type "). getNodeValue () + ". "); // Obtain the node NodeList nodeDetail = node1.getChildNodes (); // for (int j = 0; j <nodeDetail. getLength (); j ++) {// Obtain the Node detail = nodeDetail of each element. item (j); if ("code ". equals (detail. getNodeName () // output code System. out. println ("card number:" + detail. getTextContent (); else if ("pass ". equals (detail. getNodeName () // output pass System. out. println ("password:" + detail. getTextContent (); else if ("name ". equals (detail. getNodeName () // Output name System. out. println ("name:" + detail. getTextContent (); else if ("money ". equals (detail. getNodeName () // output the money System. out. println ("balance:" + detail. getTextContent () ;}}} catch (Exception e) {e. printStackTrace ();}}}
Then the XML file we tested (test. xml) should be placed in the root directory of the project. its content is:
100001
123
Li Si
1000000.00
100002
123
Zhang San
1000.00
Run the code directly and output:
Root element: Accounts
Find an account. region: type1.
Number: 100001
Password 123
Name: li si
Balance: 1000000.00
Find an account. region: type2.
Number: 100002
Password 123
Name: James
Balance: 1000.00
For more information about how to read XML files in Java, see PHP!