1

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
6
  • 1
    Do you know about JAXB.. ? Commented Feb 13, 2015 at 7:58
  • No. But I will definitely look at JAXB Commented Feb 13, 2015 at 8:11
  • Okay If you have XML . generate .xsd from it.. You can find lot online to geenrate .xsd from XML, and then You will have java classes package.. Uset that package to Unmarshal the XML .. Now You will have all the data available in form of class objects.. Commented Feb 13, 2015 at 8:13
  • Great. But the form fields may change some times. How do I handle that? The form fields should be dynamic. Can I handle with your suggestion? Commented Feb 13, 2015 at 8:16
  • Nothing to do with form fields here.. Unless untill the tag names changes.. I mean <Name>,<Address> these things should not change.. their values can change.. Commented Feb 13, 2015 at 8:48

1 Answer 1

2

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);
        } 
    }
Sign up to request clarification or add additional context in comments.

6 Comments

This solution is good only if you know the fileds in advance, if it is not the case it wont work
You can parse into a map using StAX
Added StAX based parsing example
Interesting, try String value = null; try { value = xr.getText(); } catch (Exception ex) {
I have one final query, shall I ask here Or Do I need to create a new question?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.