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>
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...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…