/
Xmls.java
728 lines (669 loc) · 22.5 KB
/
Xmls.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
package org.nutz.lang;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.nutz.lang.util.Callback2;
import org.nutz.lang.util.NutMap;
import org.nutz.lang.util.Regex;
import org.nutz.lang.util.Tag;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* XML 的快捷帮助函数
*
* @author zozoh(zozohtnt@gmail.com)
*/
public abstract class Xmls {
/**
* 帮你快速获得一个 DocumentBuilder,方便 XML 解析。
*
* @return 一个 DocumentBuilder 对象
* @throws ParserConfigurationException
*/
public static DocumentBuilder xmls() throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String FEATURE = null;
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
// Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(FEATURE, true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities
FEATURE = "http://xml.org/sax/features/external-general-entities";
dbf.setFeature(FEATURE, false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
dbf.setFeature(FEATURE, false);
// Disable external DTDs as well
FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
dbf.setFeature(FEATURE, false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
return dbf.newDocumentBuilder();
}
public static Document xml(InputStream ins) {
return xml(ins, null);
}
/**
* 快捷的解析 XML 文件的帮助方法,它会主动关闭输入流
*
* @param ins
* XML 文件输入流
* @return Document 对象
*/
public static Document xml(InputStream ins, Charset charset) {
try {
if (charset == null)
charset = Encoding.CHARSET_UTF8;
return xmls().parse(new InputSource(new InputStreamReader(ins, charset)));
}
catch (SAXException e) {
throw Lang.wrapThrow(e);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
catch (ParserConfigurationException e) {
throw Lang.wrapThrow(e);
}
finally {
Streams.safeClose(ins);
}
}
public static Document xml(File xmlFile) {
return xml(xmlFile, null);
}
/**
* 快捷的解析 XML 文件的帮助方法
*
* @param xmlFile
* XML 文件
* @return Document 对象
*/
public static Document xml(File xmlFile, Charset charset) {
InputStream ins = null;
try {
ins = new FileInputStream(xmlFile);
return xml(ins, charset);
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
}
/**
* 获取某元素下某节点的全部文本内容(去掉左右空白)
*
* @param ele
* 元素
* @param subTagName
* 子元素名
* @return 内容,null 表示子元素不存在, 空串表示元素没有对应文本内容
*/
public static String get(Element ele, String subTagName) {
Element sub = firstChild(ele, subTagName);
if (null == sub)
return null;
return getText(sub);
}
public static String getText(Element ele) {
StringBuilder sb = new StringBuilder();
joinText(ele, sb);
return Strings.trim(sb);
}
public static void joinText(Element ele, StringBuilder sb) {
if (null == ele)
return;
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node nd = nl.item(i);
switch (nd.getNodeType()) {
case Node.TEXT_NODE:
sb.append(nd.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
sb.append(nd.getNodeValue());
break;
case Node.ELEMENT_NODE:
joinText((Element) nd, sb);
break;
default:
break;
}
}
}
/**
* 获取 XML 元素内第一个子元素
*
* @param ele
* XML 元素
* @return 子元素,null 表示不存在
*/
public static Element firstChild(Element ele) {
final Element[] tag = new Element[1];
eachChildren(ele, null, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
tag[0] = cld;
Lang.Break();
}
});
return tag[0];
}
/**
* 获取 XML 元素内第一个名字所有符合一个正则表达式的子元素
*
* @param ele
* XML 元素
* @param regex
* 元素名称正则表达式
* @return 子元素,null 表示不存在
*/
public static Element firstChild(Element ele, String regex) {
final Element[] tag = new Element[1];
eachChildren(ele, regex, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
tag[0] = cld;
Lang.Break();
}
});
return tag[0];
}
/**
* 从一个 XML 元素开始,根据一条 XPath 获取一个元素
*
* @param ele
* XML 元素
* @param xpath
* 要获取的元素的 XPath
* @return 元素,null 表示不存在
*/
public static Element getEle(Element ele, String xpath) {
XPathFactory factory = XPathFactory.newInstance();
XPath xp = factory.newXPath();
try {
XPathExpression expression = xp.compile(xpath);
return (Element) expression.evaluate(ele, XPathConstants.NODE);
}
catch (XPathExpressionException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 从某个元素里获取一个指定下标的子元素
*
* @param ele
* XML 元素
* @param index
* 子元素下标(0 base)
* @return 子元素
*/
public static Element getChild(Element ele, int index) {
return getChild(ele, index, null);
}
/**
* 从某个元素里获取一个指定下标且指定名称的子元素
*
* @param ele
* XML 元素
* @param index
* 子元素下标(0 base)
* @param regex
* 元素名称的正则表达式
* @return 子元素
*/
public static Element getChild(Element ele, final int index, String regex) {
final int pos = index;
final Element[] tag = new Element[1];
eachChildren(ele, null, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
if (index >= pos) {
tag[0] = cld;
Lang.Break();
}
}
});
return tag[0];
}
/**
* 获取 XML 元素内最后一个子元素
*
* @param ele
* XML 元素
* @return 子元素,null 表示不存在
*/
public static Element lastChild(Element ele) {
final Element[] tag = new Element[1];
eachChildren(ele, null, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
tag[0] = cld;
Lang.Break();
}
}, -1);
return tag[0];
}
/**
* 获取 XML 元素内最后一个名字所有符合一个正则表达式的子元素
*
* @param ele
* XML 元素
* @param regex
* 元素名称正则表达式
* @return 子元素,null 表示不存在
*/
public static Element lastChild(Element ele, String regex) {
final Element[] tag = new Element[1];
eachChildren(ele, regex, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
tag[0] = cld;
Lang.Break();
}
}, -1);
return tag[0];
}
/**
* 获取 XML 元素内所有子元素
*
* @param ele
* XML 元素
* @return 一个子元素的列表
*/
public static List<Element> children(Element ele) {
return children(ele, null);
}
/**
* 获取 XML 元素内名字符合一个正则表达式的元素
*
* @param ele
* XML 元素
* @param regex
* 元素名称正则表达式
* @return 一个子元素的列表
*/
public static List<Element> children(Element ele, String regex) {
final List<Element> list = new ArrayList<Element>(ele.getChildNodes().getLength());
eachChildren(ele, regex, new Each<Element>() {
public void invoke(int index, Element cld, int length) {
list.add(cld);
}
});
return list;
}
/**
* 迭代 XML 元素内所有子元素
*
* @param ele
* XML 元素
* @param callback
* 回调
*/
public static void eachChildren(Element ele, Each<Element> callback) {
eachChildren(ele, null, callback);
}
/**
* 迭代 XML 元素内名字符合一个正则表达式的子元素
*
* @param ele
* XML 元素
* @param regex
* 元素名称正则表达式
* @param callback
* 回调
*/
public static void eachChildren(Element ele, String regex, final Each<Element> callback) {
Xmls.eachChildren(ele, regex, callback, 0);
}
/**
* 判断某个元素下是否有子元素
*
* @param ele
* 元素
* @param regex
* 子元素名称的正则表达式,如果为 null,则元素内如果有任意元素都会返回 false
* @return 是否有子元素
*/
public static boolean hasChild(Element ele, String regex) {
NodeList nl = ele.getChildNodes();
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node nd = nl.item(i);
if (nd instanceof Element) {
if (null == regex)
return false;
if (Regex.match(regex, ((Element) nd).getTagName()))
return true;
}
}
return false;
}
/**
* 迭代 XML 元素内名字符合一个正则表达式的子元素
*
* @param ele
* XML 元素
* @param regex
* 元素名称正则表达式
* @param callback
* 回调
* @param off
* 偏移量。0 表示从第一个迭代。 -1 表示从最后一个迭代。-2表示从倒数第二个迭代
*/
public static void eachChildren(Element ele,
String regex,
final Each<Element> callback,
int off) {
if (null == ele || null == callback)
return;
// 正则式
final Pattern p = null == regex ? null : Pattern.compile(regex);
NodeList nl = ele.getChildNodes();
// 循环子
final int len = nl.getLength();
// 每次循环执行
Callback2<Integer, Node> eachInvoke = new Callback2<Integer, Node>() {
public void invoke(Integer index, Node nd) {
if (nd instanceof Element)
try {
Element tag = (Element) nd;
if (null == p || p.matcher(tag.getTagName()).find())
callback.invoke(index, tag, len);
}
catch (ExitLoop e) {
throw Lang.wrapThrow(e);
}
catch (ContinueLoop e) {}
catch (LoopException e) {
throw Lang.wrapThrow(e);
}
}
};
try {
// 负向迭代
if (off < 0) {
for (int i = len + off; i >= 0; i--) {
eachInvoke.invoke(i, nl.item(i));
}
}
// 正向迭代
else {
for (int i = off; i < len; i++) {
eachInvoke.invoke(i, nl.item(i));
}
}
}
catch (ExitLoop e) {}
catch (RuntimeException e) {
if (e.getCause() instanceof ExitLoop)
return;
else
throw e;
}
}
/**
* 获取该 XML 元素内所有的属性的值,按照Map的形式返回
*
* @param ele
* XML 元素
* @return 所有属性的值
*/
public static Map<String, String> getAttrs(Element ele) {
NamedNodeMap nodeMap = ele.getAttributes();
Map<String, String> attrs = new HashMap<String, String>(nodeMap.getLength());
for (int i = 0; i < nodeMap.getLength(); i++) {
attrs.put(nodeMap.item(i).getNodeName(), nodeMap.item(i).getNodeValue());
}
return attrs;
}
/**
* 从 XML 元素中得到指定属性的值,如该指定属性不存在,则返回Null
*
* @param ele
* XML 元素
* @return 该指定属性的值
*/
public static String getAttr(Element ele, String attrName) {
Node node = ele.getAttributes().getNamedItem(attrName);
return node != null ? node.getNodeValue() : null;
}
/**
* 根据一个 XML 节点,将其变成一个 Map。
* <p/>
* <b>注意: 不支持混合节点</b>
*
* @param ele
* 元素
*
* @return 一个 Map 对象
*/
public static NutMap asMap(Element ele) {
return asMap(ele, false);
}
/**
* 根据一个 XML 节点,将其变成一个 Map。
* <p/>
* <b>注意: 不支持混合节点</b>
*
* @param ele
* 元素
* @param lowFirst
* 是否把所有key的首字母都小写
*
* @return 一个 Map 对象
*/
public static NutMap asMap(Element ele, final boolean lowFirst) {
return asMap(ele, lowFirst, false);
}
public static NutMap asMap(Element ele, final boolean lowFirst, final boolean dupAsList) {
return asMap(ele, lowFirst, dupAsList, null);
}
public static NutMap asMap(Element ele, final boolean lowerFirst, final boolean dupAsList, final List<String> alwaysAsList) {
return asMap(ele, new XmlParserOpts(lowerFirst, dupAsList, alwaysAsList, false));
}
public static NutMap asMap(Element ele, final XmlParserOpts opts) {
final NutMap map = new NutMap();
eachChildren(ele, new Each<Element>() {
public void invoke(int index, Element _ele, int length)
throws ExitLoop, ContinueLoop, LoopException {
String key = _ele.getNodeName();
if (opts.lowerFirst)
key = Strings.lowerFirst(key);
Map<String, Object> tmp = asMap(_ele, opts.lowerFirst, opts.dupAsList, opts.alwaysAsList);
if (!tmp.isEmpty()) {
if (opts.alwaysAsList != null && opts.alwaysAsList.contains(key)) {
map.addv2(key, tmp);
}
else if (opts.dupAsList) {
map.addv(key, tmp);
}
else {
map.setv(key, tmp);
}
return;
}
String val = getText(_ele);
if (opts.keeyBlankNode || !Strings.isBlank(val)) {
if (opts.alwaysAsList != null && opts.alwaysAsList.contains(key)) {
map.addv2(key, map);
}
else if (opts.dupAsList)
map.addv(key, val);
else
map.setv(key, val);
}
}
});
return map;
}
/**
* 将一个下面格式的 XML:
*
* <pre>
* <xml>
* <key1>value1</key1>
* <key2>value2</key2>
* </xml>
* </pre>
*
* 转换成一个 Map
*
* @param xml
* XML 字符串
*
* @return Map
*/
public static NutMap xmlToMap(String xml) {
return Xmls.asMap(Xmls.xml(Lang.ins(xml)).getDocumentElement());
}
public static NutMap xmlToMap(InputStream ins) {
return Xmls.asMap(Xmls.xml(ins).getDocumentElement());
}
public static NutMap xmlToMap(InputStream ins, final boolean lowerFirst, final boolean dupAsList, final List<String> alwaysAsList) {
return Xmls.asMap(Xmls.xml(ins).getDocumentElement(), lowerFirst, dupAsList, alwaysAsList);
}
/**
* 将一个 Map 转换成 XML 类似:
*
* <pre>
* <xml>
* <key1>value1</key1>
* <key2>value2</key2>
* </xml>
* </pre>
*
* @param map
* Map
* @return XML 字符串
*/
public static String mapToXml(Map<String, Object> map) {
return mapToXml("xml", map);
}
public static String mapToXml(String root, Map<String, Object> map) {
StringBuilder sb = new StringBuilder();
map2Tag(root, map).toXml(sb, 0);
return sb.toString();
}
protected static Tag map2Tag(String rootName, Map<String, Object> map) {
Tag rootTag = Tag.tag(rootName);
for (Map.Entry<String, Object> en : map.entrySet()) {
String key = en.getKey();
Object val = en.getValue();
List<Tag> children = obj2tag(key, val);
for (Tag child : children) {
rootTag.add(child);
}
}
return rootTag;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static List<Tag> obj2tag(String nodeName, Object val) {
List<Tag> tags = new ArrayList<Tag>();
if (null == val)
return tags;
if (val instanceof Map) {
tags.add(map2Tag(nodeName, (Map<String, Object>) val));
} else if (val instanceof Collection) {
for (Object object : (Collection)val) {
for (Tag tag : obj2tag(nodeName, object)) {
tags.add(tag);
}
}
} else {
tags.add(Tag.tag(nodeName).setText(val.toString()));
}
return tags;
}
/**
* 从一个 XML 元素开始,根据一条 XPath 获取一组元素
*
* @param ele
* XML 元素
* @param xpath
* 要获取的元素的 XPath
* @return 元素列表
*/
public static List<Element> getEles(Element ele, String xpath) {
XPathFactory factory = XPathFactory.newInstance();
XPath xp = factory.newXPath();
try {
XPathExpression expression = xp.compile(xpath);
NodeList nodes = (NodeList) expression.evaluate(ele, XPathConstants.NODESET);
List<Element> list = new ArrayList<Element>();
int len = nodes.getLength();
for (int i = 0; i < len; i++) {
Node node = nodes.item(i);
if (node instanceof Element) {
list.add((Element)node);
}
}
return list;
}
catch (XPathExpressionException e) {
throw Lang.wrapThrow(e);
}
}
public static String HEAD = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
public static class XmlParserOpts {
private boolean lowerFirst;
private boolean dupAsList;
private List<String> alwaysAsList;
private boolean keeyBlankNode;
public XmlParserOpts() {
}
public XmlParserOpts(boolean lowerFirst, boolean dupAsList, List<String> alwaysAsList, boolean keeyBlankNode) {
super();
this.lowerFirst = lowerFirst;
this.dupAsList = dupAsList;
this.alwaysAsList = alwaysAsList;
this.keeyBlankNode = keeyBlankNode;
}
public boolean isLowerFirst() {
return lowerFirst;
}
public void setLowerFirst(boolean lowerFirst) {
this.lowerFirst = lowerFirst;
}
public boolean isDupAsList() {
return dupAsList;
}
public void setDupAsList(boolean dupAsList) {
this.dupAsList = dupAsList;
}
public List<String> getAlwaysAsList() {
return alwaysAsList;
}
public void setAlwaysAsList(List<String> alwaysAsList) {
this.alwaysAsList = alwaysAsList;
}
public boolean isKeeyBlankNode() {
return keeyBlankNode;
}
public void setKeeyBlankNode(boolean keeyBlankNode) {
this.keeyBlankNode = keeyBlankNode;
}
}
}