|
3 | 3 | import com.google.common.collect.Lists;
|
4 | 4 | import com.google.common.collect.Maps;
|
5 | 5 | import com.google.common.collect.Sets;
|
6 |
| -import org.dom4j.Document; |
7 |
| -import org.dom4j.DocumentException; |
8 |
| -import org.dom4j.Element; |
9 |
| -import org.dom4j.Node; |
| 6 | +import org.dom4j.*; |
10 | 7 | import org.dom4j.io.SAXReader;
|
11 | 8 | import org.dom4j.tree.DefaultText;
|
12 | 9 | import org.xml.sax.SAXException;
|
@@ -50,14 +47,16 @@ public static Map<String, Object> xml2Map(String xmlString) {
|
50 | 47 | }
|
51 | 48 |
|
52 | 49 | private static Object element2MapOrString(Element element) {
|
53 |
| - Map<String, Object> result = Maps.newHashMap(); |
54 | 50 |
|
55 | 51 | final List<Node> content = element.content();
|
56 |
| - if (content.size() <= 1) { |
| 52 | + final Set<String> names = names(content); |
| 53 | + |
| 54 | + // 判断节点下有无非文本节点(非Text和CDATA),如无,直接取Text文本内容 |
| 55 | + if (names.size() < 1) { |
57 | 56 | return element.getText();
|
58 | 57 | }
|
59 | 58 |
|
60 |
| - final Set<String> names = names(content); |
| 59 | + Map<String, Object> result = Maps.newHashMap(); |
61 | 60 | if (names.size() == 1) {
|
62 | 61 | // 说明是个列表,各个子对象是相同的name
|
63 | 62 | List<Object> list = Lists.newArrayList();
|
@@ -90,7 +89,8 @@ private static Object element2MapOrString(Element element) {
|
90 | 89 | private static Set<String> names(List<Node> nodes) {
|
91 | 90 | Set<String> names = Sets.newHashSet();
|
92 | 91 | for (Node node : nodes) {
|
93 |
| - if (node instanceof DefaultText) { |
| 92 | + // 如果节点类型是Text或CDATA跳过 |
| 93 | + if (node instanceof DefaultText || node instanceof CDATA) { |
94 | 94 | continue;
|
95 | 95 | }
|
96 | 96 | names.add(node.getName());
|
|
0 commit comments