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")); ListempList = 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 { ListempList = 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 { ListempList = 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
总结:以上就是本篇文章的全部内容了,希望对大家有所帮助
Das obige ist der detaillierte Inhalt vonJava中解析XML的方式有哪些. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!