如何将带XML的字符串转换为HashMap



我有一块XML,它通过substring变成了String。我需要比较其中的一些数据,所以需要将其转换为HashMap。这是XML:

title="Language Dependence" totalvotes="32">

<results>        
<result level="1" value="No necessary in-game text" numvotes="0" />
<result level="2" value="Some necessary text - easily memorized or small crib sheet" numvotes="7" />
<result level="3" value="Moderate in-game text - needs crib sheet or paste ups" numvotes="22" />
<result level="4" value="Extensive use of text - massive conversion needed to be playable" numvotes="2" />
<result level="5" value="Unplayable in another language" numvotes="1" />
</results>                    
</poll>

我已经编写了HashMap代码,但它似乎不起作用。我做错了什么?

响应响应=RestAssured.get(api地址(;

String code = response.asString();
String partialCode = code.substring(15967, 16535);
String partialCodeAm = partialCode.replaceAll("/>", "");
String partialCodeAp = partialCodeAm.replaceAll("<", "");
String partialCodeAf = partialCodeAp.replaceAll(""", "");
String partialCodeAd = partialCodeAf.replaceAll("results>", "");
String partialCodeAu = partialCodeAd.replaceAll(">", "");
String partialCodeAc = partialCodeAu.replaceAll("/results>", "");
String partialCodeAk = partialCodeAc.replaceAll("/", "");
String[] parts = partialCodeAk.split(",");
Map<String, String> map = new HashMap<>();
for (String part : parts) {
String[] voteData = part.split(":");
String level = voteData[0].trim();
String numvotes = voteData[0].trim();
map.put(level, numvotes);
}

要解析XML,请使用XML解析器。其中一个更简单但功能强大的是Jsoup,它允许我们编写类似的代码

String XMLString = """
<results>
<result level="1" value="No necessary in-game text" numvotes="0" />
<result level="2" value="Some necessary text - easily memorized or small crib sheet" numvotes="7" />
<result level="3" value="Moderate in-game text - needs crib sheet or paste ups" numvotes="22" />
<result level="4" value="Extensive use of text - massive conversion needed to be playable" numvotes="2" />
<result level="5" value="Unplayable in another language" numvotes="1" />
</results>
""";
Map<String, String> map = new HashMap<>();
Elements allResultElements = Jsoup.parse(XMLString, Parser.xmlParser()).select("result");
for (Element result : allResultElements){
map.put(result.attr("level"), result.attr("numvotes"));
}
System.out.println(map);

输出:{1=0, 2=7, 3=22, 4=2, 5=1}

最新更新