Requirements Analysis:
You need to parse the returned XML format data when making a small thing that takes advantage of the API.
See article: [Development Notes] a command-line-based English-English dictionary (a cli-based EE Dictionary)
Project Address: https://github.com/hwding/seekDict
Preparatory work:
- Read documentation
- Check the relevant code
Read in the XML file into the program:
First, generate a Documentbuilder instance with Documentbuilderfactory
Documentbuilder Docmumentbuilder = Documentbuilderfactory.newinstance ();
This instance is used to read from a file, parse and construct an (XML) document
Next, use Docmumentbuilder to parse the local XML file and assign the result to an (XML) document instance
Document document = Docmumentbuilder.parse (file);
Note that this file is not declared here, and it should actually point to a local store of XML files
If the parse succeeds, the document is a valid (XML) document within the program
The lookup and reading of the node (node\nodelist) and elements (element):
Element rootelement = Document.getdocumentelement ();
Assign the entire document to rootelement as a large element first
NodeList cotent = Rootelement.getchildnodes ();
The Getchildnodes () method of the element class obtains all of the first-level nodes in the nodelist, which stores multiple node
So at this point, all the first-level nodes in the XML document are stored in the content.
If you need to continue to parse the child nodes of the first-level node, the method is the same, but converting the node class into an element class requires an instance check, otherwise there will be an error while traversing the node
1 if instanceof Element) 2 element example = (Element) content.item (i);
If the sub-node in the content is an instance of elememnt, then the type is converted and assigned to example, and the node can be further processed
Extracting the desired label node
Node def = Element.getelementsbytagname ("def"). Item (j);
Will get the J child node in all child nodes labeled "Def" under the element node
Get the content of a text node
Childnodes.item (P). gettextcontent ();
Class methods and properties (important):
See the JAVA SE 8 DOCS API
[Study notes] Parsing XML files using DOM methods in Java