Skip to content

Commit

Permalink
XML to JSON conversion - convert attributes #240
Browse files Browse the repository at this point in the history
  • Loading branch information
Gelin Luo committed Dec 21, 2020
1 parent 3ede387 commit 54ce705
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# OSGL Tool Change Log

1.26.0 - 21/Dec/2020
* XML to JSON conversion - convert attributes #240

1.25.2 - 18/Aug/2020
* Update fastjson to 1.2.73

Expand Down
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

<artifactId>osgl-tool</artifactId>
<packaging>jar</packaging>
<version>1.25.3-SNAPSHOT</version>
<version>1.26.0-SNAPSHOT</version>

<name>Java Tool</name>
<description>A simple Java toolkit</description>
Expand All @@ -43,8 +43,8 @@
<orika.version>1.5.2</orika.version>
<commons-lang3.version>3.7</commons-lang3.version>
<model-mapper.version>1.1.0</model-mapper.version>
<hutool.version>[4.1.12,)</hutool.version>
<fastjson.version>1.2.73</fastjson.version>
<hutool.version>5.5.4</hutool.version>
<fastjson.version>1.2.75</fastjson.version>
<genie.version>1.10.0</genie.version>
<jpa.version>1.0.0.Final</jpa.version>
<junit-benchmarks.version>0.7.2</junit-benchmarks.version>
Expand Down
23 changes: 22 additions & 1 deletion src/main/java/org/osgl/util/converter/XmlDocumentToJsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,16 @@

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.osgl.$;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import org.w3c.dom.*;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class XmlDocumentToJsonUtil {

Expand All @@ -46,12 +50,29 @@ static Object convert(Node node, String listItemTag) {
case Node.TEXT_NODE:
return convert(node.getTextContent());
case Node.ELEMENT_NODE:
return convert(node.getChildNodes(), listItemTag);
Object ret = convert(node.getChildNodes(), listItemTag);
if (ret instanceof JSONObject) {
((JSONObject) ret).putAll(convertAttributes(node));
} else {
((JSONArray) ret).add(C.Map("_attributes", convertAttributes(node)));
}
return ret;
default:
return null;
}
}

static Map<String, String> convertAttributes(Node node) {
NamedNodeMap attributes = node.getAttributes();
if (null == attributes) return C.EMPTY_MAP;
Map<String, String> ret = new HashMap<>();
for (int i = attributes.getLength() - 1; i >= 0; --i) {
Node attribute = attributes.item(i);
ret.put(attribute.getNodeName(), attribute.getNodeValue());
}
return ret;
}

private static Object convert(NodeList list, String listItemTag) {
int size = list.getLength();
if (1 == size) {
Expand Down

0 comments on commit 54ce705

Please sign in to comment.