Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

java - HashMap to XML syntax

Am looking in plain old java code where we can convert hashmap to xml and xml to hashmap

<key1>value1</key1>
<key2>value2</key2>

with out using any external libraries

any info or some light will help. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a sample code where I used Pattern and Matcher to find the key and value from the xml string.

Here is online demo for regex pattern.

Here is better picture of the regex pattern

<([^>]+)>([^<]*)</1>

Regular expression visualization

Debuggex Demo

I have used parenthesis (...) for grouping and 1 is used for back reference of the first matched group.


sample code:

String xml = "<key1>value1</key1><key2>value2</key2>";

// ------------------------- XML to Map -----------

Map<String, String> map = new LinkedHashMap<String, String>();
Pattern p = Pattern.compile("<([^>]+)>([^<]*)</\1>");
Matcher m = p.matcher(xml);
while (m.find()) {
    map.put(m.group(1), m.group(2));
}

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}

// ------------------------- Map to XML -----------

StringBuffer buffer = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
    buffer.append("<").append(entry.getKey()).append(">");
    buffer.append(entry.getValue());
    buffer.append("</").append(entry.getKey()).append(">");
}
System.out.println(buffer);

output:

key1:value1
key2:value2
<key1>value1</key1><key2>value2</key2>

Here is good way to convert XML into Map using DOM parser API. It's better explained in Oracle tutorial on Reading XML Data into a DOM along with lots of good example.

Note: I have added a root node to make it well-formed xml string.

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

String xml = "<root><key1>value1</key1><key2>value2</key2></root>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

Map<String, String> map = new LinkedHashMap<String, String>();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
    map.put(nodeList.item(i).getNodeName(), nodeList.item(i).getChildNodes().item(0)
            .getNodeValue());
}

Read more...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...