如何使用JAXB解组下面的xml并填充java对象。
我是这个JAXB的新手。我需要为多个客户填充java对象。我在客户列表中有两个客户需要转换为java对象。
类似于xml中提到的服务......
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<customerList><customer><name>ATNT</name><category>Network</category>
<country>USA</country><device>7600</device></customer>
<customer>
<name>cisco</name>
<category>Network</category>
<country>USA</country>
<device>ubr10k</device>
</customer>
</customerList>
<services>
<softwareServices>
<company>TCS</company>
<country>India</country>
<clients>
<bank>SBI</bank>
<insurance>LIC</insurance>
<telecom>Ericsson</telecom>
</clients>
</softwareServices>
<softwareServices>
<company>Infosys</company>
<country>India</country>
<clients>
<bank>IDBI</bank>
<insurance>Lombard</insurance>
<telecom>Airtel</telecom>
</clients>
</softwareServices>
</services>
</root>
答案 0 :(得分:0)
1。使用.xsd文件(请参阅下面的代码片段 SO_customer.xsd )
2。执行xjc:
C:\dev\jdk1.6.0_41\bin\xjc -d src SO_customer.xsd
这将生成您需要的java类
3。 unmarshall(请参阅下面的代码片段 MainClass.java )。 这将输出第一个客户的名称:“ATNT”
SO_customer.xsd (来自您提供的xml ...):
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="customerList">
<xs:complexType>
<xs:sequence>
<xs:element name="customer" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="name"/>
<xs:element type="xs:string" name="category"/>
<xs:element type="xs:string" name="country"/>
<xs:element type="xs:string" name="device"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="services">
<xs:complexType>
<xs:sequence>
<xs:element name="softwareServices" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="company"/>
<xs:element type="xs:string" name="country"/>
<xs:element name="clients">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="bank"/>
<xs:element type="xs:string" name="insurance"/>
<xs:element type="xs:string" name="telecom"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
MainClass.java :
package call;
import generated.Root;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class MainClass {
public static void main(String[] args) {
try {
File file = new File("C:\\SO\\src\\input.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root) jaxbUnmarshaller.unmarshal(file);
System.out.println(root.getCustomerList().getCustomer().get(0).getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}