簡體   English   中英

使用Apache Commons Configuration 2.5從xml文件讀取地圖的最優雅方法是什么?

[英]What is the most elegant way to read map from xml file using Apache Commons Configuration 2.5?

我和這個問題幾乎有同樣的問題。 假設我有一個類似的xml文件,我想閱讀第一張地圖:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <map>
    <entry key="favoriteSeason">summer</entry>
    <entry key="favoriteFruit">pomegranate</entry>
    <entry key="favoriteDay">today</entry>
  </map>
  <anotherMap>
    <entry key="favoriteSeason">winter</entry>
    <entry key="favoriteFruit">orange</entry>
    <entry key="favoriteDay">wednesday</entry>
    <entry key="favoriteColor">green</entry>
  </anotherMap>
</root>

注意:鍵值對的數量可能會有所不同。

使用ConfigurationNode的鏈接問題中的答案很好,但是在2.5版本中該類不存在。 遵循Apache的用戶指南,我想到了以下內容:

Configurations configurations = new Configurations();
XMLConfiguration xmlConfiguration = configurations.xml("config.xml");
Map<String, String> map = new HashMap<>();
int pairsCount = xmlConfiguration.getList(String.class, "map.entry").size();
for(int i = 0; i < pairsCount; ++i)
  map.put(xmlConfiguration.getString("map.entry(" + i + ")[@key]"), xmlConfiguration.getString("map.entry(" + i + ")"));

我覺得獲取鍵值對的數量並不是最好的方法,將對放在地圖中也不易讀。 有一個更好的方法嗎?

希望這可以幫助。

public static void main(String[] args) throws ConfigurationException {
    Configurations configurations = new Configurations();
    XMLConfiguration xmlConfiguration = configurations.xml("config.xml");
    Map<String, Map<String, String>> map = new HashMap<>();
    xmlConfiguration.getNodeModel().getRootNode().getChildren().forEach(x -> {
        Map<String, String> temp = new HashMap<>();
        x.getChildren().forEach(y -> {
            temp.put(y.getAttributes().get("key").toString(), y.getValue().toString());
        });
        map.put(x.getNodeName(), temp);
    });
    System.err.println(map);
}

您的示例的輸出映射:

 {
    anotherMap={
        favoriteDay=wednesday, 
        favoriteColor=green,
        favoriteSeason=winter, 
        favoriteFruit=orange
       },
   map={
       favoriteDay=today, 
       favoriteSeason=summer, 
       favoriteFruit=pomegranate}
    }

在這里,我正在創建一個地圖,其中將包含兩個地圖,分別對應於關鍵mapanothermap map (根據您的示例x​​ml)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM