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.readXML
Reads an XML file.XmlUtil.parseXml
Parses an XML string into a Document object.
Writing XML
XmlUtil.toStr
Converts an XML document into a String.XmlUtil.toFile
Writes an XML document to a file.
Creating XML
XmlUtil.createXml
Creates 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.cleanInvalid
Removes invalid characters from the XML text.XmlUtil.getElements
Obtains a list of child nodes based on the node name.XmlUtil.getElement
Obtains the first child node based on the node name.XmlUtil.elementText
Obtains the text content of the first child node based on the node name.XmlUtil.transElements
Converts a NodeList to a list of Element objects.
XML to Object Conversion
writeObjectAsXml
Converts a serializable object to XML and writes it to a file, overwriting any existing files.readObjectFromXml
Reads an object from XML.
Note These two methods rely heavily on JDK’s
XMLEncoder
andXMLDecoder
, 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
createXPath
Creates an XPath object.getByXPath
Reads 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.