CeccoCQ
CeccoCQ

Reputation: 3754

Java Parser XML example

enter code hereI've to deserialize this XML:

<rows profile="color">
    <head>
        <columns>
            <column width="0" align="left" type="ro" sort="str" color=""><![CDATA[#]]></column>
            <column width="80" align="left" type="ro" sort="str" color=""><![CDATA[Targa]]></column>
            <column width="100" align="left" type="ro" sort="str" color=""><![CDATA[Telaio]]></column>
            <column width="150" align="left" type="ro" sort="str" color=""><![CDATA[Tipo]]></column>
            <column width="70" align="left" type="ro" sort="str" color=""><![CDATA[Archivio]]></column>
            <column width="220" align="left" type="co" sort="str" color=""><![CDATA[Commenti]]><option value="A">A</option><option value="B">B</option><option value="C">C</option></column>
            <column width="180" align="left" type="ed" sort="str" color=""><![CDATA[Destinatario]]></column>
        </columns>
    </head>
    <row>
        <cell><![CDATA[775]]></cell>
        <cell><![CDATA[AA000AA]]></cell>
        <cell><![CDATA[RTGGSHHJSJSNN]]></cell>
        <cell><![CDATA[CDP]]></cell>
        <cell><![CDATA[18]]></cell>
        <cell><![CDATA[...]]></cell>
        <cell><![CDATA[ ]]></cell>
    </row>
</rows>

But I haven't a defined class, how can I do it? I would use xstream library, but I don't know how use it.

EDIT:

But if I want to create a destination class, how I create it? I should have something like:

public class Rows { 
    private Head head; 
    private Row[] row; 
}

public class Head { 
    private Columns columns;
} 

public class Columns {
    private Column column; // How can I get attributes?
}

public class Row {
    private String [] cell;
}

and how can I use xstream after?

Upvotes: 2

Views: 1631

Answers (3)

RicardoS
RicardoS

Reputation: 2118

Take a look on JAXB. ( http://jaxb.java.net/ )

It's a great lib for read/write a XML into/from classes. I know there are some plugins for it. I'm almost sure you can generate/create classes from a XML file or create the XML from annotaded classes.

Some examples: http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/JAXBUsing3.html

Hello World: http://jaxb.java.net/tutorial/section_1_3-Hello-World.html

Upvotes: 2

Jhonathan
Jhonathan

Reputation: 1611

Use SAX

SAX parser is work differently with DOM parser, it either load any XML document into memory nor create any object representation of the XML document. Instead, the SAX parser use callback function (org.xml.sax.helpers.DefaultHandler) to informs clients of the XML document structure.

if you want create a class from XML use Digester

Example

Upvotes: 0

npinti
npinti

Reputation: 52185

Since you do not have a target class to which XStream can deserialize, you will have to use other XML parsers.

You can take a look at StAX. You can find how to use it here and here.

Upvotes: 0

Related Questions