在 Java 春季引导中从 XML 加载属性的正确方法

我有XML文件,其中存储了国家/地区。每个国家/地区元素都具有区域、次区域、国家/地区代码等属性。我有服务,应该解析XML并根据提供的国家/地区名称获取区域。有没有办法将数据从xml加载和使用到内存中,这样我就不需要每次想要获取国家/地区的区域时都解析XML?我不想使用枚举,因为我希望有可更新的xml列表,该列表仅在应用程序启动或首次使用我的服务时解析一次。因此,在XML更新之后,服务器重新启动就足够了,而无需重建应用程序来更新枚举。如何实现这一点?


慕妹3242003
浏览 70回答 1
1回答

白板的微信

我碰巧有一个类似的解决方案,很容易复制/粘贴到一个工作示例中。如果您的 XML 如下所示:<countries>&nbsp; &nbsp; <country name="England" region="Europe"&nbsp; &nbsp; &nbsp; &nbsp; subregion="Western Europe" countryCode="eng" />&nbsp; &nbsp; <country name="Scotland" region="Europe"&nbsp; &nbsp; &nbsp; &nbsp; subregion="West Europe" countryCode="sco" /></countries>你有一个类型,因此:Countrypublic class Country {&nbsp; &nbsp; private String name;&nbsp; &nbsp; private String region;&nbsp; &nbsp; private String subregion;&nbsp; &nbsp; private String countryCode;&nbsp; &nbsp; // getters and setters}然后将以下依赖项添加到项目中:com.fasterxml.jackson.dataformat:jackson-dataformat-xml<dependency>&nbsp; &nbsp; <groupId>com.fasterxml.jackson.dataformat</groupId>&nbsp; &nbsp; <artifactId>jackson-dataformat-xml</artifactId></dependency>和这段代码:public class JacksonXml {&nbsp; &nbsp; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {&nbsp; &nbsp; &nbsp; &nbsp; InputStream is = JacksonXml.class.getResourceAsStream("/countries.xml");&nbsp; &nbsp; &nbsp; &nbsp; XmlMapper xmlMapper = new XmlMapper();&nbsp; &nbsp; &nbsp; &nbsp; List<Country> countries = xmlMapper.readValue(is, new TypeReference<List<Country>>() {&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Country> nameToCountry = countries.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Country::getName, Function.identity()));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(nameToCountry.get("England")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getRegion());&nbsp; &nbsp; }}将产生:Europe
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java