* initial commit

* initial commit

* code cleanup

* code cleanup

* code cleanup

* code cleanup

* code review comments addressed

* pom version

* code review comments

* formatting updated

* updated as per code review comments
This commit is contained in:
Shahul Basha 2023-11-20 21:50:44 -05:00 committed by GitHub
parent 111dcccb92
commit 94595ea000
6 changed files with 271 additions and 0 deletions

View File

@ -46,6 +46,16 @@
<artifactId>underscore</artifactId>
<version>${underscore.version}</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
@ -82,6 +92,8 @@
<dom4j.version>2.1.3</dom4j.version>
<json.version>20230227</json.version>
<underscore.version>1.89</underscore.version>
<xstream.version>1.4.18</xstream.version>
<jaxb.version>2.3.3</jaxb.version>
</properties>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.xml.tohashmap;
public class Employee {
private String id;
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.xml.tohashmap;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employees")
public class Employees {
private List<Employee> employeeList;
@XmlElement(name = "employee")
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
}

View File

@ -0,0 +1,124 @@
package com.baeldung.xml.tohashmap;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.github.underscore.U;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;
public class XmlToHashMap {
public Map<String, Employee> xmlToHashMapUsingXstream(String xml) {
XStream xStream = new XStream();
xStream.alias("employees", List.class);
xStream.alias("employee", Employee.class);
xStream.addPermission(AnyTypePermission.ANY);
List<Employee> employees = (List<Employee>) xStream.fromXML(xml);
return employees.stream()
.collect(Collectors.toMap(Employee::getId, Function.identity()));
}
public Map<String, Employee> xmlToHashMapUsingUnderscore(String xml) {
Map<String, Employee> employeeMap = new HashMap<>();
Map<String, Object> employeeList = (Map<String, Object>) U.fromXmlMap(xml)
.get("employees");
List<LinkedHashMap<String, String>> list = (List<LinkedHashMap<String, String>>) employeeList.get("employee");
parseXmlToMap(employeeMap, list);
return employeeMap;
}
public Map<String, Employee> xmlToHashMapUsingJackson(String xml) throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
Map<String, Employee> employeeMap = new HashMap<>();
Map<String, Object> map = xmlMapper.readValue(xml, Map.class);
List<LinkedHashMap<String, String>> list = (List<LinkedHashMap<String, String>>) map.get("employee");
parseXmlToMap(employeeMap, list);
return employeeMap;
}
public Map<String, Employee> xmlToHashMapUsingJAXB(String xmlData) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Employees.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employees employees = (Employees) unmarshaller.unmarshal(new StringReader(xmlData));
return employees.getEmployeeList()
.stream()
.collect(Collectors.toMap(Employee::getId, Function.identity()));
}
public Map<String, Employee> xmlToHashMapUsingDOMParserXpath(String xmlData) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlData)));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression xPathExpr = xpath.compile("/employees/employee");
NodeList nodes = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
HashMap<String, Employee> map = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Element node = (Element) nodes.item(i);
Employee employee = new Employee();
employee.setId(node.getElementsByTagName("id")
.item(0)
.getTextContent());
employee.setFirstName(node.getElementsByTagName("firstName")
.item(0)
.getTextContent());
employee.setLastName(node.getElementsByTagName("lastName")
.item(0)
.getTextContent());
map.put(employee.getId(), employee);
}
return map;
}
private static void parseXmlToMap(Map<String, Employee> employeeMap, List<LinkedHashMap<String, String>> list) {
list.forEach(empMap -> {
Employee employee = new Employee();
for (Map.Entry<String, String> key : empMap.entrySet()) {
switch (key.getKey()) {
case "id":
employee.setId(key.getValue());
break;
case "firstName":
employee.setFirstName(key.getValue());
break;
case "lastName":
employee.setLastName(key.getValue());
break;
default:
break;
}
}
employeeMap.put(employee.getId(), employee);
});
}
}

View File

@ -0,0 +1,12 @@
<employees>
<employee>
<id>654</id>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
<employee>
<id>776</id>
<firstName>Steve</firstName>
<lastName>Smith</lastName>
</employee>
</employees>

View File

@ -0,0 +1,71 @@
package com.baeldung.xml.tohashmap;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class XmlToHashMapUnitTest {
private XmlToHashMap xmlToHashMap;
private static final String TEST_XML_PATH = "src/main/resources/xml/xmltohashmap/test.xml";
@BeforeEach
void setUp() {
xmlToHashMap = new XmlToHashMap();
}
@Test
void whenUsingXstream_thenHashMapShouldBeCreated() throws IOException {
Map<String, Employee> employeeMap = xmlToHashMap.xmlToHashMapUsingXstream(getXml());
verify(employeeMap);
}
@Test
void whenUsingUnderscore_thenHashMapShouldBeCreated() throws IOException {
Map<String, Employee> employeeMap = xmlToHashMap.xmlToHashMapUsingUnderscore(getXml());
verify(employeeMap);
}
@Test
void whenUsingJackson_thenHashMapShouldBeCreated() throws IOException {
Map<String, Employee> employeeMap = xmlToHashMap.xmlToHashMapUsingJackson(getXml());
verify(employeeMap);
}
@Test
void whenUsingJAXB_thenHashMapShouldBeCreated() throws IOException, JAXBException {
Map<String, Employee> employeeMap = xmlToHashMap.xmlToHashMapUsingJAXB(getXml());
verify(employeeMap);
}
@Test
void whenUsingDOMXpath_thenHashMapShouldBeCreated() throws Exception {
Map<String, Employee> employeeMap = xmlToHashMap.xmlToHashMapUsingDOMParserXpath(getXml());
verify(employeeMap);
}
private void verify(Map<String, Employee> employeeMap) {
Employee employee1 = employeeMap.get("654");
Employee employee2 = employeeMap.get("776");
Assertions.assertEquals("John", employee1
.getFirstName());
Assertions.assertEquals("Doe", employee1
.getLastName());
Assertions.assertEquals("Steve", employee2
.getFirstName());
Assertions.assertEquals("Smith", employee2
.getLastName());
}
private String getXml() throws IOException {
return new String(Files.readAllBytes(Paths.get(TEST_XML_PATH)));
}
}