I found this on google, but I don't want to use XStream, because it causes to much overhead in my environment. I only needed to parse a file and since I did not find anything I like I created my own simple solution for parsing a file of the format that you describe. So here is my solution:
public class XmlToMapUtil {
public static Map<String, String> parse(InputSource inputSource) throws SAXException, IOException, ParserConfigurationException {
final DataCollector handler = new DataCollector();
SAXParserFactory.newInstance().newSAXParser().parse(inputSource, handler);
return handler.result;
}
private static class DataCollector extends DefaultHandler {
private final StringBuilder buffer = new StringBuilder();
private final Map<String, String> result = new HashMap<String, String>();
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
final String value = buffer.toString().trim();
if (value.length() > 0) {
result.put(qName, value);
}
buffer.setLength(0);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
buffer.append(ch, start, length);
}
}
}
Here are a couple of TestNG+FEST Assert Tests:
public class XmlToMapUtilTest {
@Test(dataProvider = "provide_xml_entries")
public void parse_returnsMapFromXml(String xml, MapAssert.Entry[] entries) throws Exception {
// execution
final Map<String, String> actual = XmlToMapUtil.parse(new InputSource(new StringReader(xml)));
// evaluation
assertThat(actual)
.includes(entries)
.hasSize(entries.length);
}
@DataProvider
public Object[][] provide_xml_entries() {
return new Object[][]{
{"<root />", new MapAssert.Entry[0]},
{
"<root><a>aVal</a></root>", new MapAssert.Entry[]{
MapAssert.entry("a", "aVal")
},
},
{
"<root><a>aVal</a><b>bVal</b></root>", new MapAssert.Entry[]{
MapAssert.entry("a", "aVal"),
MapAssert.entry("b", "bVal")
},
},
{
"<root> \t <a>\taVal </a><b /></root>", new MapAssert.Entry[]{
MapAssert.entry("a", "aVal")
},
},
};
}
}