解析XML并填充到Map中

时间:2012-08-08 19:40:44

标签: java xml xml-parsing

我有xml如下。

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

XML包含大量员工。我仅提到简化。

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

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

3 个答案:

答案 0 :(得分:4)

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
        }
    }

}

答案 1 :(得分:1)

使用XStream等库。 List<Employee>Map更适合。

答案 2 :(得分:1)

我们可以使用Xstream简单地映射它。

XStream xStream = new XStream(new DomDriver());
xStream.alias("Employees", Employees.class);
xStream.registerConverter(new MapEntryConverter());
employeesMap = (Map<String, String>) xStream.fromXML(queryXML);

创建一个将XML解组为Map对象的转换器

private static class MapEntryConverter implements Converter {
        public boolean canConvert(Class clazz) {
            return clazz.equals(Employees.class);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
            AbstractMap<String, String> map = (AbstractMap<String, String>) value;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                writer.startNode(entry.getKey().toString());
                writer.setValue(entry.getValue().toString());
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Map<String, String> map = new HashMap<String, String>();

            while (reader.hasMoreChildren()) {
                reader.moveDown();
                map.put(reader.getAttribute(1), reader.getValue());
                reader.moveUp();
            }
            return map;
        }
    }

创建员工和员工类,如下所示。

private class Employees{
        List<Employee> employees;
    }
    private class Employee{
        private String id;
        private String value;
}

希望这适合你。