Use JAXB.unmarshal()
to simply create Java objects from XML.
By default it is very liberal.
Quoting from the javadoc:
In addition, the unmarshal methods have the following characteristic:
- Schema validation is not performed on the input XML. The processing will try to continue even if there are errors in the XML, as much as possible. Only as the last resort, this method fails with DataBindingException.
So what JAXB.unmarshal()
does is it tries to "transfer" as much data from XML to Java as possible, and it doesn't care if there is no Java field for an XML element or attribute, and it also doesn't care if there is a Java field for which there is no XML element or attribute.
Example
Let's try to unmarshal the following XML to an instance of java.awt.Point
:
<p hi="Yo">
<y>123</y>
<peach>weor</peach>
</p>
The Java code:
String s = "<p hi="Yo"><y>123</y><peach>weor</peach></p>";
Point p = JAXB.unmarshal(new StringReader(s), Point.class);
System.out.println(p); // Prints "java.awt.Point[x=0,y=123]"
We told JAXB.unmarshal()
to parse a java.awt.Point
instance. The input XML contains an element <y>
which can be matched with Point.y
so an int
was parsed and set to Point.y
. No XML data was found for Point.x
so it was not touched. There were no match for the attribute hi
and the XML element <peach>
, so they were simply not used for anything.
We got absolutely no Exception
here, and the most that was possible was parsed and transferred from XML to Java.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…