-2

I hava a XML file containing Infos:

<Datas>
<Data type="DL  ">
    <IndexLine>
        <Field name="TerminalNum" string=""/>
    </IndexLine>
    <BusinessLine>
        <Field name="MachineNum" string=" "/>
        <Field name="StuffNum" string=" "/>
        <Field name="psw" string=""/>
    </BusinessLine>
</Data>

<Data type="PM  ">
    <IndexLine>
        <Field name="TerminalNum" string=""/>
    </IndexLine>
    <BusinessLine>
        <Field name="MachineNum" string=" "/>
        <Field name="StuffNum" string=" "/>
        <Field name="psw" string=""/>
    </BusinessLine>
</Data>
</Datas>

How can I convert the above XML into Map such as HashMap<String,Data>. The key is the value of attribute "type", and Data is a bean that defines the node <Data> </Data> content.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
desertboat
  • 145
  • 1
  • 2
  • 9
  • 1
    Possible duplicate of [how to parse xml to hashmap?](http://stackoverflow.com/questions/27547292/how-to-parse-xml-to-hashmap) – LF00 Sep 19 '16 at 06:00
  • What I want is to use fromXml() function to generate a bean object directly just like using GSON or other simple tools. Can I implement the interface Converter to do this? – desertboat Sep 19 '16 at 07:53

3 Answers3

0

The following answer can give an idea how to convert the xml to java object. It may not give the exact solution.

  1. Create the 'Data' class, IndexedLine, BusinessLine classes Eg:

    public class Data {
        private IndexedLine indexedLine;
        private BusinessLine businessLine;
    
        // setter and getter
    }
    
    public class IndexedLine {
        private Field filed;
    
        // setter and getter
    }
    
    public class BusinessLine {
        private Field filed;
    
        // setter and getter
    }
    
    public class Field {
        private String name;
        private String string;
    
        // setter and getter
    }
    
  2. Write java code to get the objects from xml.

    XStream xstream = new XStream();
    xstream.alias("data", Data.class);
    xstream.alias("indexedLine", IndexedLine.class);    
    xstream.alias("businessLine", BusinessLine.class);
    Data data = (Data)xstream.fromXML(xml);
    

The above code is a sample one. May not work exactly, You need to do little modifications to work it. Please find the xstream api and example here: http://x-stream.github.io/alias-tutorial.html

Sudhakar
  • 3,104
  • 2
  • 27
  • 36
0

there is some technologies to convert xml to java object and java object to xml.

kindly see the below like xStream.github.io

It may help to understand you how to convert from xml to a hashMap

Parthasarathy
  • 308
  • 2
  • 10
0

You can use JAXB to unmarshall(converting XML to Java objects) the XML and then prepare the HashMap as per the requirement.

JohnDoe
  • 1
  • 2