Java中解析XML的方式有哪些
更新时间:2023-12-18前言
XML (eXtensible Markup Language) 可扩展标记语言的出现使得数据之间可以互相传递,因为它可以描述被传递数据的结构和规范。在Java开发中,我们也经常需要遇到解析XML文档的情况,本篇文章将会介绍Java中解析XML的方式。
方式一:DOM解析
DOM (Document Object Model) 解析是树形的结构,将xml文档中所有的内容读入内存中,然后可以随意遍历该节点树实现任何对该xml文档的操作。
public void parseXmlByDom(String fileName) { try { // 1. 加载文件并创建DocumentBuilder实例 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); InputStream inputStream=new FileInputStream(fileName); Document document=builder.parse(inputStream); // 2. 获取节点 NodeList nodeList=document.getElementsByTagName("book"); for (int i=0; i < nodeList.getLength(); i++) { // 3. 获取节点的值 Node node=nodeList.item(i); if (node.getNodeType()==Node.ELEMENT_NODE) { Element element=(Element) node; System.out.println("Title:" + element.getElementsByTagName("title").item(0).getTextContent()); System.out.println("Author:" + element.getElementsByTagName("author").item(0).getTextContent()); System.out.println("Year:" + element.getElementsByTagName("year").item(0).getTextContent()); System.out.println("Price:" + element.getElementsByTagName("price").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } }
方式二:SAX解析
SAX (Simple API for XML) 解析是基于事件的解析,它会顺序解析xml文档,当遇到开始标签 和结束标签 时,会通过回调函数返回相应的信息。
public void parseXmlBySax(String fileName) { try { SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); MySaxHandler handler=new MySaxHandler(); InputStream inputStream=new FileInputStream(fileName); parser.parse(inputStream, handler); } catch (Exception e) { e.printStackTrace(); } } public class MySaxHandler extends DefaultHandler { private String currentValue; private Book book; private ListbookList=new ArrayList (); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("book".equals(qName)) { book=new Book(); book.setId(attributes.getValue("id")); } currentValue=""; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if ("title".equals(qName)) { book.setTitle(currentValue); } else if ("author".equals(qName)) { book.setAuthor(currentValue); } else if ("year".equals(qName)) { book.setYear(currentValue); } else if ("price".equals(qName)) { book.setPrice(currentValue); } else if ("book".equals(qName)) { bookList.add(book); book=null; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { currentValue +=new String(ch, start, length); } }
方式三:JAXB解析
JAXB (Java Architecture for XML Binding) 基于实体类的方式解析xml文档,可以将xml文档和java类实现绑定,避免了手写解析xml文档的繁琐。
@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="bookstore") public class BookStore { @XmlElement(name="book") private ListbookList; // getter setter } @XmlRootElement(name="book") public class Book { @XmlAttribute(name="id") private String id; @XmlElement(name="title") private String title; @XmlElement(name="author") private String author; @XmlElement(name="year") private String year; @XmlElement(name="price") private String price; // getter setter } public void parseXmlByJaxb(String fileName) { try { JAXBContext ctx=JAXBContext.newInstance(BookStore.class); Unmarshaller um=ctx.createUnmarshaller(); InputStream inputStream=new FileInputStream(fileName); BookStore bookStore=(BookStore) um.unmarshal(inputStream); } catch (Exception e) { e.printStackTrace(); } }
方式四:JDOM解析
JDOM是纯java的操作XML库,它提供了构建、查询以及修改XML文档的API,与DOM的主要区别是,JDOM使用的是Java集合类的方式,而不是建立一个文档树模型(DOM)对象。
public void parseXmlByJdom(String fileName) { SAXBuilder saxBuilder=new SAXBuilder(); Document document; try { document=saxBuilder.build(new FileInputStream(fileName)); Element rootElement=document.getRootElement(); ListbookElementList=rootElement.getChildren("book"); for (Element bookElement : bookElementList) { System.out.println("Title:" + bookElement.getChildText("title")); System.out.println("Author:" + bookElement.getChildText("author")); System.out.println("Year:" + bookElement.getChildText("year")); System.out.println("Price:" + bookElement.getChildText("price")); } } catch (Exception e) { e.printStackTrace(); } }
总结
Java中解析XML的方式主要有: DOM解析,SAX解析,JAXB解析,JDOM解析,每种解析方式都有其优缺点,根据需求和场景的不同,可以选择合适的解析方式来完成xml文档的操作。