问题
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/"><?xml version="1.0" encoding="utf-8" ?
><MyList><Obj>Im obj 1</Obj><Obj>Im obj
1</Obj></MyList></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
回答1:
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/\"><?xml version=\"1.0\" encoding=\"utf-8\" ?><MyList><Obj>Im obj 1</Obj><Obj>Im obj1</Obj></MyList></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 );
}
}
来源:https://stackoverflow.com/questions/19993327/how-to-parse-unmarshall-the-string-xml-inside-a-string-xml-into-a-java-object