我正在嘗試為我的專案實作多語言界面,為此我想從 XML 檔案加載 3 種語言的資料。問題是,當我想讀取值時,我只能使用我不想要的readValue(file,MyClass.class)來做到這一點,因為我想直接將資料提取到一個集合中并對其進行迭代,而不是到一個物件中。例如,在 XML 檔案中,我想直接提取帶有“english”的欄位,然后遍歷其值。我可以對“羅馬尼亞語”或“德語”做同樣的事情。我發現為我擁有的每個視窗創建一個新類是沒有用的......有沒有辦法直接提取每種語言并迭代它的元素?
這是我的 XML 代碼:
?<?xml version="1.0" encoding="utf-8"?>
<langauges>
<romanian>
<flight_number>Numar zbor:</flight_number>
<depart_airport>Aeroport plecare:</depart_airport>
<destination>Destinatie:</destination>
<flight_time>Timpul de zbor:</flight_time>
<username>Utilizator:</username>
<password>Parola:</password>
<login>Log In</login>
<search_depart_destination_time>Cautare dupa aeroport de plecare/destinatie si timp</search_depart_destination_time>
<see_price_free_seats_2_locations>Vezi preturi si locuri libere intre 2 locatii</see_price_free_seats_2_locations>
<search_after_flight_number>Cauta dupa numarul zborului</search_after_flight_number>
</romanian>
<english>
<flight_number>Flight number:</flight_number>
<depart_airport>Depart airport:</depart_airport>
<destination>Destination:</destination>
<flight_time>Flight time:</flight_time>
<username>Username:</username>
<password>Password:</password>
<login>Log In</login>
<search_depart_destination_time>Search after depart/destination airport and time</search_depart_destination_time>
<see_price_free_seats_2_locations>See price and free seats between 2 locations</see_price_free_seats_2_locations>
<search_after_flight_number>Search after flight number</search_after_flight_number>
</english>
<german>
<flight_number>Flug Nummer:</flight_number>
<depart_airport>Abflug flughafen:</depart_airport>
<destination>Bestimmungsort:</destination>
<flight_time>Flugzeit:</flight_time>
<username>Nutzername:</username>
<password>Passwort:</password>
<login>Anmeldung</login>
<search_depart_destination_time>Suchen zwischen abflug/bestimmungsort und zeit</search_depart_destination_time>
<see_price_free_seats_2_locations>Sehen preis und frei plaetze zwischen 2 oerten</see_price_free_seats_2_locations>
<search_after_flight_number>Suchen ueber Flug nummer</search_after_flight_number>
</german>
</langauges>
在這里,我沒有成功的Java方法:
XmlMapper xmlMapper = new XmlMapper();
File file = new File("languages.xml");
String xml = Files.readString(file.toPath());
String s = xmlMapper.readValue(xml, String.class);
uj5u.com熱心網友回復:
我認為您可能想要一個可以動態更改的可迭代結構,而無需更改您的類。在這種情況下,我建議使用地圖。
Map<String, Map<String, String>>xmlMap = xmlMapper.readValue(xml, new TypeReference<Map<String, Map<String, String>>>() {});
或者干脆
Map<String, Map<String, String>>xmlMap = xmlMapper.readValue(xml, Map.class);
但我更喜歡前一個,因為它更干凈。然后你可以這樣稱呼他們
String password = xmlMap.get("german").get("password");
System.out.println(password);
在其他編程語言(如 JavaScript)中,物件只是一個映射,無需太多努力即可動態更改。
我正在考慮的一種情況是有一個包含語言的下拉串列,在您選擇它之后,您可以遍歷該語言中的元素,也許您的語言需要更多或更少的欄位,在這種情況下,地圖是一個不錯的選擇。
希望對您有所幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468546.html
