1 回答
TA贡献1883条经验 获得超3个赞
我碰巧有一个类似的解决方案,很容易复制/粘贴到一个工作示例中。
如果您的 XML 如下所示:
<countries>
<country name="England" region="Europe"
subregion="Western Europe" countryCode="eng" />
<country name="Scotland" region="Europe"
subregion="West Europe" countryCode="sco" />
</countries>
你有一个类型,因此:Country
public class Country {
private String name;
private String region;
private String subregion;
private String countryCode;
// getters and setters
}
然后将以下依赖项添加到项目中:
com.fasterxml.jackson.dataformat:jackson-dataformat-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
和这段代码:
public class JacksonXml {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
InputStream is = JacksonXml.class.getResourceAsStream("/countries.xml");
XmlMapper xmlMapper = new XmlMapper();
List<Country> countries = xmlMapper.readValue(is, new TypeReference<List<Country>>() {
});
Map<String, Country> nameToCountry = countries.stream()
.collect(Collectors.toMap(Country::getName, Function.identity()));
System.out.println(nameToCountry.get("England")
.getRegion());
}
}
将产生:
Europe
添加回答
举报