<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Java 讀取 XML – Java DOM 解析器示例 > 原文: [https://howtodoinjava.com/xml/read-xml-dom-parser-example/](https://howtodoinjava.com/xml/read-xml-dom-parser-example/) 在此 *Java xml 解析器教程*中,學習**用 Java 中的 DOM 解析器**讀取 xml。 DOM 解析器旨在將 XML 作為內存中的對象圖(樹狀結構)使用 – 稱為“**文檔對象模型(DOM)**”。 首先,解析器遍歷輸入的 XML 文件并創建與 XML 文件中的節點相對應的 **DOM** 對象。 這些 DOM 對象以樹狀結構鏈接在一起。 一旦解析器完成了解析過程,我們就會從中獲得這種樹狀 DOM 對象結構。 現在,我們可以根據需要來回遍歷 DOM 結構 - 從中獲取/更新/刪除數據。 ```java Table of Contents 1\. DOM Parser API -Import XML-related packages -Create a DocumentBuilder -Create a Document from a file or stream -Validate Document structure -Extract the root element -Examine attributes -Examine sub-elements 2\. Read XML with DOM parser 3\. Read data to POJO objects 4\. Parse "unknown" xml with DOM parser ``` > 閱讀更多: [DOM 解析器和 SAX 解析器](//howtodoinjava.com/xml/dom-vs-sax-parser-in-java/ "DOM Vs SAX Parser in Java")之間的區別 出于示例目的,我們將在所有代碼示例中解析 xml 內容。 ```java <employees> <employee id="111"> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <location>India</location> </employee> <employee id="222"> <firstName>Alex</firstName> <lastName>Gussin</lastName> <location>Russia</location> </employee> <employee id="333"> <firstName>David</firstName> <lastName>Feezor</lastName> <location>USA</location> </employee> </employees> ``` ## 1\. DOM 解析器 API 讓我們記下一些主要步驟,以**創建并使用 DOM 解析器**來解析 Java 中的 XML 文件。 ![DOM Parser in Action](https://img.kancloud.cn/05/27/05279e309c086cdb508e74d33b9a9a31_456x207.png) DOM 解析器的實際應用 #### 1.1 導入 dom 解析器包 我們將需要首先在我們的應用中導入 dom 解析器包。 ```java import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; ``` #### 1.2 創建`DocumentBuilder` 下一步是創建`DocumentBuilder`對象。 ```java DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); ``` #### 1.3 從 xml 文件創建`Document`對象 將 XML 文件讀取到`Document`對象。 ```java Document document = builder.parse(new File( file )); ``` #### 1.4 驗證文件結構 XML 驗證是可選的,但最好在開始解析之前進行驗證。 ```java Schema schema = null; try { String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; SchemaFactory factory = SchemaFactory.newInstance(language); schema = factory.newSchema(new File(name)); } catch (Exception e) { e.printStackStrace(); } Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); ``` #### 1.5 提取根元素 我們可以使用以下代碼從 XML 文檔中獲取根元素。 ```java Element root = document.getDocumentElement(); ``` #### 1.6 檢查屬性 我們可以使用以下方法檢查 xml 元素屬性。 ```java element.getAttribute("attributeName") ; //returns specific attribute element.getAttributes(); //returns a Map (table) of names/values ``` #### 1.7 檢查子元素 子元素可以以下方式查詢。 ```java node.getElementsByTagName("subElementName") //returns a list of sub-elements of specified name node.getChildNodes() //returns a list of all child nodes ``` ## 2.使用 DOM 解析器讀取 XML 在下面的示例代碼中,我假設用戶已經知道`employees.xml`文件的結構(它的節點和屬性); 因此,示例直接開始獲取信息并開始在控制臺中打印信息。 在現實生活中的應用中,我們將這些信息用于某些實際目的,而不是在控制臺上打印并離開。 ```java //Get Document Builder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Build Document Document document = builder.parse(new File("employees.xml")); //Normalize the XML Structure; It's just too important !! document.getDocumentElement().normalize(); //Here comes the root node Element root = document.getDocumentElement(); System.out.println(root.getNodeName()); //Get all employees NodeList nList = document.getElementsByTagName("employee"); System.out.println("============================"); for (int temp = 0; temp < nList.getLength(); temp++) { Node node = nList.item(temp); System.out.println(""); //Just a separator if (node.getNodeType() == Node.ELEMENT_NODE) { //Print each employee's detail Element eElement = (Element) node; System.out.println("Employee id : " + eElement.getAttribute("id")); System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent()); System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent()); System.out.println("Location : " + eElement.getElementsByTagName("location").item(0).getTextContent()); } } ``` 程序輸出: ```java employees ============================ Employee id : 111 First Name : Lokesh Last Name : Gupta Location : India Employee id : 222 First Name : Alex Last Name : Gussin Location : Russia Employee id : 333 First Name : David Last Name : Feezor Location : USA ``` ## 3.將數據讀取到 POJO 對象 現實生活中另一個應用的要求可能是使用上面示例代碼中提取的信息填充 DTO 對象。 我寫了一個簡單的程序來幫助您了解如何輕松完成它。 假設我們必須填充`Employee`對象,其定義如下。 ```java public class Employee { private Integer id; private String firstName; private String lastName; private String location; //Setters and Getters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", location=" + location + "]"; } } ``` 現在查看示例代碼以填充員工對象列表。 就像在代碼之間插入幾行,然后將值復制到 DTO 而不是控制臺中一樣簡單。 Java 程序,用于使用 DOM 解析器讀取 XML 文件。 ```java public class PopulateDTOExamplesWithParsedXML { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { List<Employee> employees = parseEmployeesXML(); System.out.println(employees); } private static List<Employee> parseEmployeesXML() throws ParserConfigurationException, SAXException, IOException { //Initialize a list of employees List<Employee> employees = new ArrayList<Employee>(); Employee employee = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("employees.xml")); document.getDocumentElement().normalize(); NodeList nList = document.getElementsByTagName("employee"); for (int temp = 0; temp < nList.getLength(); temp++) { Node node = nList.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; //Create new Employee Object employee = new Employee(); employee.setId(Integer.parseInt(eElement.getAttribute("id"))); employee.setFirstName(eElement.getElementsByTagName("firstName").item(0).getTextContent()); employee.setLastName(eElement.getElementsByTagName("lastName").item(0).getTextContent()); employee.setLocation(eElement.getElementsByTagName("location").item(0).getTextContent()); //Add Employee to list employees.add(employee); } } return employees; } } ``` 程序輸出。 ```java [Employee [id=111, firstName=Lokesh, lastName=Gupta, location=India], Employee [id=222, firstName=Alex, lastName=Gussin, location=Russia], Employee [id=333, firstName=David, lastName=Feezor, location=USA]] ``` ## 4.使用 DOM 解析器解析“未知” xml 上一個示例顯示了在編寫代碼時,我們如何遍歷具有已知或幾乎不知道的結構的 XML 文檔。 在某些情況下,我們可能必須以某種方式編寫代碼,以便即使在編碼時假定的 XML 結構存在某些差異,程序也必須能夠正常運行。 在這里,我們遍歷 XML 文檔樹中存在的所有元素。 我們可以添加我們的知識并修改代碼,以便在遍歷樹時只要獲得所需信息,我們就可以使用它。 ```java public class ParseUnknownXMLStructure { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //Get Document Builder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Build Document Document document = builder.parse(new File("employees.xml")); //Normalize the XML Structure; It's just too important !! document.getDocumentElement().normalize(); //Here comes the root node Element root = document.getDocumentElement(); System.out.println(root.getNodeName()); //Get all employees NodeList nList = document.getElementsByTagName("employee"); System.out.println("============================"); visitChildNodes(nList); } //This function is called recursively private static void visitChildNodes(NodeList nList) { for (int temp = 0; temp < nList.getLength(); temp++) { Node node = nList.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent()); //Check all attributes if (node.hasAttributes()) { // get attributes names and values NamedNodeMap nodeMap = node.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) { Node tempNode = nodeMap.item(i); System.out.println("Attr name : " + tempNode.getNodeName()+ "; Value = " + tempNode.getNodeValue()); } if (node.hasChildNodes()) { //We got more childs; Let's visit them as well visitChildNodes(node.getChildNodes()); } } } } } } ``` 程序輸出: ```java employees ============================ Node Name = employee; Value = Lokesh Gupta India Attr name : id; Value = 111 Node Name = firstName; Value = Lokesh Node Name = lastName; Value = Gupta Node Name = location; Value = India Node Name = employee; Value = Alex Gussin Russia Attr name : id; Value = 222 Node Name = firstName; Value = Alex Node Name = lastName; Value = Gussin Node Name = location; Value = Russia Node Name = employee; Value = David Feezor USA Attr name : id; Value = 333 Node Name = firstName; Value = David Node Name = lastName; Value = Feezor Node Name = location; Value = USA ``` 這就是 **Java XML DOM 解析器**的概念。 如果不清楚或需要更多說明,請給我評論。 [下載源碼](https://drive.google.com/file/d/0B7yo2HclmjI4d1dwd2hZb19IbEU/edit?usp=sharing "dom parser example sourcecode") 學習愉快! 參考: [http://www.w3c.org/DOM/](http://www.w3c.org/DOM/ "DOM")
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看