0
# XML Operations
1
2
XML parsing, manipulation, and serialization utilities through the XmlUtil class.
3
4
## Capabilities
5
6
### XML Document Reading
7
8
Parse XML from various sources into DOM Document objects.
9
10
```java { .api }
11
/**
12
* Read XML document from file
13
* @param file XML file to read
14
* @return parsed Document object
15
*/
16
public static Document readXML(File file);
17
18
/**
19
* Read XML from string (file path or XML content)
20
* @param pathOrContent file path or XML content string
21
* @return parsed Document object
22
*/
23
public static Document readXML(String pathOrContent);
24
25
/**
26
* Read XML document from input stream
27
* @param inputStream XML input stream
28
* @return parsed Document object
29
*/
30
public static Document readXML(InputStream inputStream);
31
32
/**
33
* Read XML document from reader
34
* @param reader XML character reader
35
* @return parsed Document object
36
*/
37
public static Document readXML(Reader reader);
38
39
/**
40
* Read XML document from InputSource
41
* @param source XML input source
42
* @return parsed Document object
43
*/
44
public static Document readXML(InputSource source);
45
```
46
47
**Usage Examples:**
48
49
```java
50
import cn.hutool.core.util.XmlUtil;
51
import org.w3c.dom.Document;
52
import java.io.File;
53
54
// Read from file
55
Document doc = XmlUtil.readXML(new File("config.xml"));
56
57
// Read from XML string
58
String xmlContent = "<root><item>value</item></root>";
59
Document docFromString = XmlUtil.readXML(xmlContent);
60
61
// Read from classpath file
62
Document docFromPath = XmlUtil.readXML("/config/app.xml");
63
```
64
65
### SAX Parsing
66
67
Parse XML using SAX parser with custom content handlers.
68
69
```java { .api }
70
/**
71
* Read XML using SAX parser from file
72
* @param file XML file to read
73
* @param contentHandler SAX content handler
74
*/
75
public static void readBySax(File file, ContentHandler contentHandler);
76
77
/**
78
* Read XML using SAX parser from reader
79
* @param reader XML character reader
80
* @param contentHandler SAX content handler
81
*/
82
public static void readBySax(Reader reader, ContentHandler contentHandler);
83
84
/**
85
* Read XML using SAX parser from input stream
86
* @param source XML input stream
87
* @param contentHandler SAX content handler
88
*/
89
public static void readBySax(InputStream source, ContentHandler contentHandler);
90
```
91
92
### XML Serialization
93
94
Convert DOM nodes and documents to string representations.
95
96
```java { .api }
97
/**
98
* Convert XML node to string
99
* @param doc XML node to convert
100
* @return XML string representation
101
*/
102
public static String toStr(Node doc);
103
104
/**
105
* Convert XML document to string
106
* @param doc XML document to convert
107
* @return XML string representation
108
*/
109
public static String toStr(Document doc);
110
111
/**
112
* Convert XML node to formatted string
113
* @param doc XML node to convert
114
* @param isPretty whether to format with indentation
115
* @return XML string representation
116
*/
117
public static String toStr(Node doc, boolean isPretty);
118
119
/**
120
* Convert XML node to string with charset and formatting
121
* @param doc XML node to convert
122
* @param charset character encoding
123
* @param isPretty whether to format with indentation
124
* @return XML string representation
125
*/
126
public static String toStr(Node doc, String charset, boolean isPretty);
127
128
/**
129
* Convert XML node to string with full options
130
* @param doc XML node to convert
131
* @param charset character encoding
132
* @param isPretty whether to format with indentation
133
* @param omitXmlDeclaration whether to omit XML declaration
134
* @return XML string representation
135
*/
136
public static String toStr(Node doc, String charset, boolean isPretty, boolean omitXmlDeclaration);
137
```
138
139
**Usage Examples:**
140
141
```java
142
import cn.hutool.core.util.XmlUtil;
143
import org.w3c.dom.Document;
144
145
Document doc = XmlUtil.readXML("<root><item>value</item></root>");
146
147
// Basic string conversion
148
String xmlString = XmlUtil.toStr(doc); // Compact XML
149
150
// Pretty formatted XML
151
String prettyXml = XmlUtil.toStr(doc, true);
152
153
// Custom charset and formatting
154
String customXml = XmlUtil.toStr(doc, "UTF-8", true, false);
155
```
156
157
### XML Writing
158
159
Write XML documents to files and streams.
160
161
```java { .api }
162
/**
163
* Write XML node to output stream
164
* @param node XML node to write
165
* @param out output stream
166
* @param charset character encoding
167
* @param indent indentation size
168
*/
169
public static void write(Node node, OutputStream out, String charset, int indent);
170
171
/**
172
* Write XML node to writer
173
* @param node XML node to write
174
* @param writer character writer
175
* @param charset character encoding
176
* @param indent indentation size
177
*/
178
public static void write(Node node, Writer writer, String charset, int indent);
179
180
/**
181
* Write XML node with declaration control
182
* @param node XML node to write
183
* @param out output stream
184
* @param charset character encoding
185
* @param indent indentation size
186
* @param omitXmlDeclaration whether to omit XML declaration
187
*/
188
public static void write(Node node, OutputStream out, String charset, int indent, boolean omitXmlDeclaration);
189
```
190
191
### XPath Operations
192
193
Execute XPath expressions on XML documents.
194
195
```java { .api }
196
/**
197
* Get element by XPath expression
198
* @param doc XML document
199
* @param expression XPath expression
200
* @return matching element or null
201
*/
202
public static Element getElementByXPath(Document doc, String expression);
203
204
/**
205
* Get elements by XPath expression
206
* @param doc XML document
207
* @param expression XPath expression
208
* @return NodeList of matching elements
209
*/
210
public static NodeList getElementListByXPath(Document doc, String expression);
211
212
/**
213
* Get object by XPath expression
214
* @param doc XML document
215
* @param expression XPath expression
216
* @param returnType expected return type
217
* @return XPath evaluation result
218
*/
219
public static Object getByXPath(Document doc, String expression, QName returnType);
220
```
221
222
**Usage Examples:**
223
224
```java
225
import cn.hutool.core.util.XmlUtil;
226
import org.w3c.dom.Document;
227
import org.w3c.dom.Element;
228
import org.w3c.dom.NodeList;
229
230
String xml = "<root><users><user id='1'>Alice</user><user id='2'>Bob</user></users></root>";
231
Document doc = XmlUtil.readXML(xml);
232
233
// XPath queries
234
Element userElement = XmlUtil.getElementByXPath(doc, "//user[@id='1']");
235
NodeList allUsers = XmlUtil.getElementListByXPath(doc, "//user");
236
String userName = (String) XmlUtil.getByXPath(doc, "//user[@id='1']/text()", XPathConstants.STRING);
237
```
238
239
### XML Entity Operations
240
241
Handle XML entity encoding and decoding.
242
243
```java { .api }
244
/**
245
* Escape XML special characters
246
* @param string string to escape
247
* @return escaped XML string
248
*/
249
public static String escape(String string);
250
251
/**
252
* Unescape XML entities to original characters
253
* @param string string with XML entities
254
* @return unescaped string
255
*/
256
public static String unescape(String string);
257
258
/**
259
* Remove invalid XML characters
260
* @param string string to clean
261
* @return string with invalid XML characters removed
262
*/
263
public static String cleanInvalid(String string);
264
```
265
266
**Usage Examples:**
267
268
```java
269
import cn.hutool.core.util.XmlUtil;
270
271
// Entity handling
272
String original = "Hello <world> & \"quotes\"";
273
String escaped = XmlUtil.escape(original); // "Hello <world> & "quotes""
274
String unescaped = XmlUtil.unescape(escaped); // "Hello <world> & \"quotes\""
275
276
// Clean invalid characters
277
String withInvalid = "Hello\u0001World\u0008";
278
String cleaned = XmlUtil.cleanInvalid(withInvalid); // "HelloWorld"
279
```
280
281
### Document Creation
282
283
Create new XML documents and elements.
284
285
```java { .api }
286
/**
287
* Create new XML document
288
* @return new empty Document
289
*/
290
public static Document createXml();
291
292
/**
293
* Create document with root element
294
* @param rootElementName root element name
295
* @return new Document with root element
296
*/
297
public static Document createXml(String rootElementName);
298
299
/**
300
* Get document builder factory
301
* @return DocumentBuilderFactory instance
302
*/
303
public static DocumentBuilderFactory getDocumentBuilderFactory();
304
305
/**
306
* Get document builder
307
* @return DocumentBuilder instance
308
*/
309
public static DocumentBuilder getDocumentBuilder();
310
```
311
312
## Common Types
313
314
```java { .api }
315
// XML processing types
316
import org.w3c.dom.Document;
317
import org.w3c.dom.Element;
318
import org.w3c.dom.Node;
319
import org.w3c.dom.NodeList;
320
import org.xml.sax.ContentHandler;
321
import org.xml.sax.InputSource;
322
import javax.xml.namespace.QName;
323
import javax.xml.xpath.XPathConstants;
324
325
// XML entity constants
326
public static final String NBSP = " ";
327
public static final String AMP = "&";
328
public static final String QUOTE = """;
329
public static final String APOS = "'";
330
public static final String LT = "<";
331
public static final String GT = ">";
332
```