Reputation: 818
I am using Jackson api to parse xml object.
<BESAPI xsi:noNamespaceSchemaLocation="BESAPI.xsd">
<Employee Resource="https://abc:52311/api/employee/100"/>
<Employee Resource="https://abc:52311/api/employee/200"/>
<Employee Resource="https://abc:52311/api/employee/300"/>
<Employee Resource="https://abc:52311/api/employee/400"/>
</BESAPI>
this is the structure of xml records. I want to get list of all resources as String. How can I achieve it using Jackson api?
Upvotes: 2
Views: 4561
Reputation: 325
SimpleXml can do this:
final String data = ...
final SimpleXml simple = new SimpleXml();
final Element element = simple.fromXml(data);
for (final Element employee : element.children) {
System.out.println(employee.attributes.get("Resource"));
}
Will output:
https://abc:52311/api/employee/100
https://abc:52311/api/employee/200
https://abc:52311/api/employee/300
https://abc:52311/api/employee/400
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>
Upvotes: 0
Reputation: 10147
First you need to write some Java classes modeling your XML content.
The classes get @JacksonXml...
annotations to tell Jackson the mapping between XML and Java.
These annotations are especially important when a Java name is different from the XML name.
One class is for representing the <BESAPI>
root element:
@JacksonXmlRootElement(localName = "BESAPI")
public class BESAPI {
@JacksonXmlProperty(isAttribute = true, localName = "noNamespaceSchemaLocation", namespace = XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI)
private String noNamespaceSchemaLocation;
@JacksonXmlProperty(isAttribute = false, localName = "Employee")
@JacksonXmlElementWrapper(useWrapping = false)
private List<Employee> employees;
// public getters and setters (omitted here for brevity)
}
and another class for representing the <Employee>
element
public class Employee {
@JacksonXmlProperty(isAttribute=true, localName="Resource")
private String resource;
// public getters and setters (omitted here for brevity)
}
Then you can use Jackson's XmlMapper
for reading XML content.
XmlMapper xmlMapper = new XmlMapper();
File file = new File("example.xml");
BESAPI besApi = xmlMapper.readValue(file, BESAPI.class);
for (Employee employee : besApi.getEmployees()) {
System.out.println(employee.getResource());
}
Upvotes: 4