Zin Yackvaa
Zin Yackvaa

Reputation: 905

Xml string to objects using JAXB

How can I create a java object class with an xml-string using JAXB or any other way? I would like to pass the xml-string and generate a class for mapping. I have a nested string like such:

<?xml version="1.0"?>
    <tag1>
        <tag2>
            <tag3>
                <tag4>read me</tag4>
            </tag3>
        </tag2>
    </tag1>

Upvotes: 2

Views: 98

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

Assuming that your XML won't change of structure over time, you can generate a XSD file from a tool like http://www.freeformatter.com/xsd-generator.html.

Here it gives me:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="tag1">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="tag2">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="tag3">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:string" name="tag4"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Then you can store this schema on your local file system, and launch the command xjc myFile.xsd which will generate JAXB files for you.

More details about xjc, here

Upvotes: 1

Related Questions