今天研究了unmarshal,说白了其实就是xml文档读操作。其中遇到一个Unmarshaller.unmarshal方法返回实际对象的类型问题。起初个人一直觉得应该返回xml文档根元素类型的实例,通过实例操作发现不仅其然。
例子1:
xml schema:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="book">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="ISBN" type="xsd:int"/>
<xsd:element name="publisher" type="xsd:string"/>
<xsd:element name="edition" type="xsd:int"/>
<xsd:element type="xsd:double" name="price"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
对应xml 文档:
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="src/simple.xsd">
<name>hello china</name>
<author>owen</author>
<ISBN>1860</ISBN>
<publisher>objectiva</publisher>
<edition>1</edition>
<price>10.0</price>
</book>
解析类:
/*************************the code can make sure the root element of XML document automatically
JAXBContext context = JAXBContext.newInstance("com.objectiva.JAXBTesting.book");
Unmarshaller unMarshaller = context.createUnmarshaller();
Object object = unMarshaller.unmarshal(new File("simple.xml"));
if(object instanceof Book)
{
例子1:
xml schema:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="book">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="ISBN" type="xsd:int"/>
<xsd:element name="publisher" type="xsd:string"/>
<xsd:element name="edition" type="xsd:int"/>
<xsd:element type="xsd:double" name="price"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
对应xml 文档:
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="src/simple.xsd">
<name>hello china</name>
<author>owen</author>
<ISBN>1860</ISBN>
<publisher>objectiva</publisher>
<edition>1</edition>
<price>10.0</price>
</book>
解析类:
/*************************the code can make sure the root element of XML document automatically
JAXBContext context = JAXBContext.newInstance("com.objectiva.JAXBTesting.book");
Unmarshaller unMarshaller = context.createUnmarshaller();
Object object = unMarshaller.unmarshal(new File("simple.xml"));
if(object instanceof Book)
{