gpt4 book ai didi

java - 解析 XML 并填充到 Map 中

转载 作者:行者123 更新时间:2023-12-01 16:33:32 24 4
gpt4 key购买 nike

我的 xml 如下。

<Employees>
<Employee id="1">Chuck</Employee>
<Employee id="2">Al</Employee>
<Employee id="3">Kiran</Employee>
</Employees>

XML 包含大量员工。我提到这些只是为了简单起见。

解析此 xml 并填充到 map 中的最佳方法是什么? map 应包含 ID 和名称对。

请提供代码以便更好地理解。

最佳答案

XStream answer看起来有很多代码。您可以使用 JDK/JRE 中的 StAX API 执行类似以下操作:

package forum11871952;

import java.io.FileReader;
import java.util.*;
import javax.xml.stream.*;

public class Demo {

public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("src/forum11871952/input.xml"));
xsr.nextTag(); // advance to Employees tag
xsr.nextTag(); // advance to first Employer element
Map<String,String> map = new HashMap<String,String>();
while(xsr.getLocalName().equals("Employee")) {
map.put(xsr.getAttributeValue("", "id"), xsr.getElementText());
xsr.nextTag(); // advance to next Employer element
}
}

}

关于java - 解析 XML 并填充到 Map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com