您好,登錄后才能下訂單哦!
這篇文章主要介紹了Java中解析XML的方式是什么,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
java解析XML的方式有使用DOM解析通過DOM對象以樹狀結構連接在一起;使用SAX 解析它是遇到不同元素時會逐行解析;使用StAX解析會從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 解析
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 Parser
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的方式是什么內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。