-2

I have an xml that looks like this (fragment).

<struct>
    <member>
        <name>last_name</name>
        <value>
            <string></string>
        </value>
    </member>
    <member>
        <name>payment_method</name>
        <value>
            <int>1</int>
        </value>
    </member>
</struct>

How can I convert it to a java class? It has over 100 elements and 40 more like this to convert, so manually parsing it is out of the question :)

The problem is that parsers can't recognize the values that are enclosed in name and value tags, or I don't know how to use it. All the examples online asume you have something like <age>78</age> not <name>age<name/> <value>78</value>

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • Use one of the *many* XML parsers built into Java: DOM, SAX, StAX, JAXB. Or use one of the even more proliferate 3rd-party XML parser libraries available (search the web if you want to find them). – Andreas Aug 12 '16 at 22:41
  • Possible duplicate of [how to parse xml to java object?](http://stackoverflow.com/questions/16364547/how-to-parse-xml-to-java-object) – Aleksandar Đokić Aug 12 '16 at 22:43
  • Yeah i know about the parsers, the problem is that they cant populate the class because the names and values of the fields are enclosed in name and value tag srespectevly. The problem is to make a parser (preferably jax) to understand the weird scema. I searched the web ofc but i couldnt find any example. – Nicholas Papadakos Aug 12 '16 at 22:58

2 Answers2

0

Use the maven-jaxb2-plugin. It generates unsexy code to parse XML from an XML schema (XSD file). If you don't have an XSD you can generate it from sample data at this online generator. So after generating your XSD adding the plugin to your POM and configuring it (where is the XSD and which package to generate code to) you will be able to run mvn generate-sources. It will generate a set of classes mostly in a single Java file capable of parsing all your XML. It generates a runtime structure of POJOs representing the XML nodes that you can traverse to extract any necessary information.

Daniel Cerecedo
  • 6,071
  • 4
  • 38
  • 51
0

It appeared to be easier to create a class that takes all the values and creates a new XML document from scratch that can be easily parsed with jax or some other parser.