During project creation, many parameters need to be modified without modifying the program to implement some parameter changes. The first thing we think of is to read the XML file. Therefore, you only need to change the parameter values in the XML file of the project. Here, I will give a brief description as follows:
Try {
Documentbuilderfactory factory = documentbuilderfactory
. Newinstance (); // getDocumentBuilderFactory
(Define the factory so that the application can get the parser that generates the DOM object tree from the XML document ).
Documentbuilder builder = factory. newdocumentbuilder (); // obtain the DOM document instance from the XML document.
Java. Io. File F = new file ("file path"); // specify a file
Document document = builder. parse (f); // The interface indicates the entire HTML or XML document.
Element rootelement = Document. getdocumentelement (); // This is a convenient attribute that allows you to directly access the child nodes of the document element.
Nodelist list = rootelement. getelementsbytagname ("field"); // returns all descendants with the given tag name in document orderElements
OfNodeList
Element element = (element) List. Item (0); // extractElement
Nodelist yearlist = element. getelementsbytagname ("Cols"); // obtainGiven a tag named "Cols" under ElementNodeList
Text text = (text) yearlist. Item (0). getfirstchild (); // getNodeList
First subnode
Nodelist yearlist1 = element. getelementsbytagname ("rows"); "); // get thisGiven in element with the name "rows"NodeList
Text text1 = (text) yearlist1.item (0). getfirstchild (); // getNodeList
First subnode
Hang = integer. parseint (text. getdata (); // get the node Value
Lie = integer. parseint (text1.getdata ());
} Catch (exception e ){
System. Out. println ("exception:" + E. getmessage ());
}
My XML documents are as follows:
<Hxw>
<Field ID = "1">
<Cols> 5 </Cols>
<Rows> 10 </rows>
</Field>
</Hxw>
Of course, if there are more than one field, it can be read through the for loop.
Now let's talk about it here. You are welcome to give your valuable comments :)