DOM解析器演示使用DocumentBuilder。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DOM解析器演示使用DocumentBuilder。相关的知识,希望对你有一定的参考价值。
Code is to demonstrate the use of DocumentBuilder to parse the XML file. And retrieve the data from it.
import java.io.File; 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.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DocumentBuilderDemo { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); NodeList nodeList = root.getElementsByTagName("to"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } nodeList = root.getElementsByTagName("from"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } nodeList = root.getElementsByTagName("body"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } } } /* The simple.xml file that we used for parsing in above example. <?xml version="1.0"?> <msg> <note> <to>Tom</to> <from>Prince</from> <heading>Reminder</heading> <body>Hello how are u?</body> </note> <note> <to>Sania</to> <from>Prince</from> <heading>Joking</heading> <body>Welcome!!!</body> </note> </msg> */
以上是关于DOM解析器演示使用DocumentBuilder。的主要内容,如果未能解决你的问题,请参考以下文章