java解析XML的方式有使用DOM解析透過DOM物件以樹狀結構連接在一起;使用SAX 解析它是遇到不同元素時會逐行解析;使用StAX解析會從XML中提取所需的資料
XML是一種通用的資料交換格式,它的平台無關性、語言無關性、系統無關性、給資料整合與互動帶來了極大的方便。接下來將會在文章中為大家具體介紹在Java中解析XML的方式,具有一定的參考作用,希望對大家有所幫助
##【推薦課程:XML教學】
#使用DOM解析##DOM解析器主要用於在記憶體中使用XML作為物件圖(樹狀結構) 也就是文件物件模型(DOM)。首先解析器遍歷輸入XML檔案並建立與XML檔案中的節點相對應的DOM物件。這些DOM物件以樹狀結構連結在一起。一旦解析器完成了解析過程,就會從中得到這個類似樹的DOM物件結構。
範例:在所有程式碼範例中解析xml內容
public class DOMParserDemo { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( ClassLoader.getSystemResourceAsStream("xml/employee.xml")); List<Employee> empList = new ArrayList<>(); NodeList nodeList = document.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Employee emp = new Employee(); emp.id = node.getAttributes(). getNamedItem("id").getNodeValue(); NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node cNode = childNodes.item(j); if (cNode instanceof Element) { String content = cNode.getLastChild(). getTextContent().trim(); switch (cNode.getNodeName()) { case "firstName": emp.firstName = content; break; case "lastName": emp.lastName = content; break; case "location": emp.location = content; break; } } } empList.add(emp); } } for (Employee emp : empList) { System.out.println(emp); } } } class Employee{ String id; String firstName; String lastName; String location; @Override public String toString() { return firstName+" "+lastName+"("+id+")"+location; } }
Rakesh Mishra(111)Bangalore John Davis(112)Chennai Rajesh Sharma(113)Pune
SAX Parser與DOM解析器的不同之處在於SAX解析器不會將完整的XML載入到記憶體中,而是在遇到不同的元素時,它逐行解析XML,c觸發不同的事件,例如:開啟標記,結束標記,字元數據,評論等。
使用SAX Parser解析XML的程式碼如下:
import java.util.ArrayList; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXParserDemo { public static void main(String[] args) throws Exception { SAXParserFactory parserFactor = SAXParserFactory.newInstance(); SAXParser parser = parserFactor.newSAXParser(); SAXHandler handler = new SAXHandler(); parser.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"), handler); for ( Employee emp : handler.empList){ System.out.println(emp); } } } class SAXHandler extends DefaultHandler { List<Employee> empList = new ArrayList<>(); Employee emp = null; String content = null; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch(qName){ case "employee": emp = new Employee(); emp.id = attributes.getValue("id"); break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { switch(qName){ case "employee": empList.add(emp); break; case "firstName": emp.firstName = content; break; case "lastName": emp.lastName = content; break; case "location": emp.location = content; break; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { content = String.copyValueOf(ch, start, length).trim(); } } class Employee { String id; String firstName; String lastName; String location; @Override public String toString() { return firstName + " " + lastName + "(" + id + ")" + location; } }
Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune
#StAX用於XML的Streaming API,而StAX Parser與SA的不同之處在於SAX Parser。 StAX解析器也是一種與SAX解析器也是有所不同的
SAX Parser會推送數據,但StAX解析器會從XML中提取所需的數據。 StAX解析器將遊標維持在文件中的目前位置,允許提取遊標處可用的內容,而SAX解析器在遇到某些資料時發出事件。
XMLInputFactory和XMLStreamReader是兩個可用來載入XML檔案的類別。當我們使用XMLStreamReader讀取XML檔案時,事件會以整數值的形式生成,然後將這些事件與XMLStreamConstants中的常數進行比較。以下程式碼顯示如何使用StAX解析器解析XML:
import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class StaxParserDemo { public static void main(String[] args) throws XMLStreamException { List<Employee> empList = null; Employee currEmp = null; String tagContent = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader( ClassLoader.getSystemResourceAsStream("xml/employee.xml")); while(reader.hasNext()){ int event = reader.next(); switch(event){ case XMLStreamConstants.START_ELEMENT: if ("employee".equals(reader.getLocalName())){ currEmp = new Employee(); currEmp.id = reader.getAttributeValue(0); } if("employees".equals(reader.getLocalName())){ empList = new ArrayList<>(); } break; case XMLStreamConstants.CHARACTERS: tagContent = reader.getText().trim(); break; case XMLStreamConstants.END_ELEMENT: switch(reader.getLocalName()){ case "employee": empList.add(currEmp); break; case "firstName": currEmp.firstName = tagContent; break; case "lastName": currEmp.lastName = tagContent; break; case "location": currEmp.location = tagContent; break; } break; case XMLStreamConstants.START_DOCUMENT: empList = new ArrayList<>(); break; } } for ( Employee emp : empList){ System.out.println(emp); } } } class Employee{ String id; String firstName; String lastName; String location; @Override public String toString(){ return firstName+" "+lastName+"("+id+") "+location; } }
Rakesh Mishra(111) Bangalore John Davis(112) Chennai Rajesh Sharma(113) Pune
以上是Java中解析XML的方式有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!