XML解析器在java中获取Name和Value对的结果

时间:2015-02-13 07:56:35

标签: java xml parsing xml-parsing nsxmlparser

我需要解析动态生成的XML文件。因此,想要在名称和值对中解析xml结果,并将其插入到某些Hashmap中。那么解析机制在名称,值对中解析XML是否容易且更健壮?

我的XML看起来像,

<Address>
    <Name>Rahul</Name>
    <ID>2345</ID>
    <City>Pune</City>
    <Street>Gandhi Nagar</Street>
</Address>

我需要将解析结果作为

Name:Rahul
ID:2345
City:Pune
Street:Gandhi Nagar

1 个答案:

答案 0 :(得分:2)

我会使用JAXB

class Address {
    @XmlElement(name="Name")
    private String name;
    @XmlElement(name="ID")
    private String id;
    public String getName() {
        return name;
    }
    public String getID() {
        return id;
    }
}

public class Test { 

    public static void main(String[] args) throws Exception {
        Address addr = JAXB.unmarshal(new File("address.xml"), Address.class);
    }
}

如果您事先不知道字段,可以使用StAX在Map中解析:

    Map<String, String> map = new HashMap<>();
    XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("1.xml"));
    while(xr.hasNext()) {
        int e = xr.next();
        if (e == XMLStreamReader.START_ELEMENT) {
            String name = xr.getLocalName();
            xr.next();
            String value = xr.getText();
            map.put(name, value);
        } 
    }