Question

Im newbie on parsing/umarshalling string xml to java object. I just want to know how to get the string xml inside a string xml and convert to java object.

Here is my string xml from a HTTP GET:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">&lt;?xml version="1.0" encoding="utf-8" ?    
&gt;&lt;MyList&gt;&lt;Obj&gt;Im obj 1&lt;/Obj&gt;&lt;Obj&gt;Im obj       
1&lt;/Obj&gt;&lt;/MyList&gt;</string>

I notice stackoverflow is removing the root element which is the "string" and just displaying
<?xml version="1.0" encoding="utf-8" ?> <MyList> <Obj>Im obj 1</Obj> <Obj>Im obj 2</Obj> </MyList> right away if i didn't put this string xml inside a code block.

I'm trying to use JDom 2 but no luck. It only get the root element but not the children.

I also used JAXB:

I can get the root element but not the children. Here is my code:

JAXBContext jc = JAXBContext.newInstance(myPackage.String.class);           
Unmarshaller unmarshaller = jc.createUnmarshaller(); 
JAXBElement<MyList> jaxbElement = unmarshaller.unmarshal(new StreamSource(new   
ByteArrayInputStream(byteArray)), MyList.class); 

System.out.println(jaxbElement.getClass()); --> this will print myPackage.MyList                                                  

MyList myList = (MyList) jaxbElement.getValue();
System.out.println("myList.Obj = " + myList.getObjs().size()); --> this will return 0
Was it helpful?

Solution

I just got a JAXB variant working:

public class XmlParser
{
    @XmlRootElement( name = "string", namespace = "http://tempuri.org/" )
    @XmlAccessorType( XmlAccessType.FIELD )
    static class MyString
    {
        @XmlValue
        String string;
    }

    @XmlRootElement( name = "MyList" )
    @XmlAccessorType( XmlAccessType.FIELD )
    static class MyList
    {
        @XmlElement( name = "Obj" )
        List<String> objs = new ArrayList<>();
    }

    public static void main( String[] args ) throws JAXBException
    {
        String s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                + "<string xmlns=\"http://tempuri.org/\">&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;&lt;MyList&gt;&lt;Obj&gt;Im obj 1&lt;/Obj&gt;&lt;Obj&gt;Im obj1&lt;/Obj&gt;&lt;/MyList&gt;</string>";

        JAXBContext context = JAXBContext.newInstance( MyString.class, MyList.class );
        Unmarshaller unmarshaller = context.createUnmarshaller();

        MyString myString = (MyString) unmarshaller.unmarshal( new StringReader( s ) );
        MyList myList = (MyList) unmarshaller.unmarshal( new StringReader( myString.string ) );

        System.out.println( myList.objs );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top