我使用Jackson api来解析xml对象。
<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>
这是xml记录的结构。我想获得所有资源的列表作为字符串。如何使用Jackson api实现它?
答案 0 :(得分:2)
首先,您需要编写一些建模XML内容的Java类。
课程获得@JacksonXml...
注释告诉Jackson XML和Java之间的映射。
当Java名称与XML名称不同时,这些注释尤为重要。
一个类用于表示<BESAPI>
根元素:
@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)
}
和另一个用于表示<Employee>
元素的类
public class Employee {
@JacksonXmlProperty(isAttribute=true, localName="Resource")
private String resource;
// public getters and setters (omitted here for brevity)
}
然后您可以使用Jackson的XmlMapper
来阅读XML内容。
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());
}
答案 1 :(得分:0)
SimpleXml可以做到这一点:
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"));
}
将输出:
https://abc:52311/api/employee/100
https://abc:52311/api/employee/200
https://abc:52311/api/employee/300
https://abc:52311/api/employee/400
从Maven Central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>