Search code examples
javaxmlparsingxml-parsingnsxmlparser

XML parser to get result in Name and Value pair in java


I need to parse the dynamically generated XML files. So want to parse the xml results in Name and Value pair and will insert in to some Hashmap. So which parsing mechanism is easy and more robust to parse the XML in Name, value pair?

My XML looks like,

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

I need to get the parsing result as,

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

Solution

  • I would use 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);
        }
    }
    

    If you dont know fields in advance you can parse in Map using StAX:

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