XmlUtil
Background
In daily coding, besides JSON, we are most familiar with the XML format. Generally, the first thing we think of is to introduce the Dom4j package, but we are unaware that JDK has already encapsulated XML parsing and construction tools: w3c dom. However, due to the cumbersome API operations, Hutool provides the XmlUtil to simplify the process of creating, reading, and writing XML.
Usage
Reading XML
There are two methods for reading XML:
XmlUtil.readXMLReads an XML file.XmlUtil.parseXmlParses an XML string into a Document object.
Writing XML
XmlUtil.toStrConverts an XML document into a String.XmlUtil.toFileWrites an XML document to a file.
Creating XML
XmlUtil.createXmlCreates an XML document. The created XML defaults to UTF-8 encoding, and the process of modifying the encoding occurs during the toStr and toFile methods. That is, the encoding is only defined when the XML is converted to text.
XML Operations
Through the following tool methods, you can complete basic node reading operations.
XmlUtil.cleanInvalidRemoves invalid characters from the XML text.XmlUtil.getElementsObtains a list of child nodes based on the node name.XmlUtil.getElementObtains the first child node based on the node name.XmlUtil.elementTextObtains the text content of the first child node based on the node name.XmlUtil.transElementsConverts a NodeList to a list of Element objects.
XML to Object Conversion
writeObjectAsXmlConverts a serializable object to XML and writes it to a file, overwriting any existing files.readObjectFromXmlReads an object from XML.
Note These two methods rely heavily on JDK’s
XMLEncoderandXMLDecoder, and there must be a pair for generation and parsing (following a fixed format), or it will fail if using other conversion from XML to Bean.
XPath Operations
For more information on XPath, refer to the article: https://www.ibm.com/developerworks/cn/xml/x-javaxpathapi.html
createXPathCreates an XPath object.getByXPathReads XML nodes and other information through XPath traversal.
Example:
<?xml version="1.0" encoding="utf-8"?>
<returnsms>
<returnstatus>Success</returnstatus>
<message>ok</message>
<remainpoint>1490</remainpoint>
<taskID>885</taskID>
<successCounts>1</successCounts>
</returnsms>Document docResult = XmlUtil.readXML(xmlFile);
// Result: "ok"
Object value = XmlUtil.getByXPath("//returnsms/message", docResult, XPathConstants.STRING);Summary
XmlUtil is simply a tool encapsulation of w3c dom that simplifies operations on DOM, reducing the difficulty of working with DOM if your project relies heavily on XML, it is still recommended to use the Dom4j framework.