Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...