我正在尝试使用JAXB从xml中检索值。下面详细说明:
我的OrderValidation.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OrderValidation>
<OrderType name="Activation-Activation">
<Product>
<Name>TV_SAT</Name>
<ActionCode>ADD</ActionCode>
</Product>
</OrderType>
<OrderType name="Change Owner-Change Owner">
<Product>
<Name>TV_SAT_EQUIPMENT</Name>
<ActionCode>EXISTING</ActionCode>
</Product>
</OrderType>
</OrderValidation>
这是我的Orderxml.java
@XmlRootElement(name ="OrderValidation")
public class Orderxml
{
private String name;
private String Product;
private String OrderType;
public Orderxml() {}
public Orderxml(String name, String productclass, String ordertype)
{
super();
this.name = name;
this.Product = productclass;
this.OrderType = ordertype;
}
@XmlAttribute
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@XmlElement
public String getProductName()
{
return Product;
}
public void setProductName(String productclass)
{
this.Product = productclass;
}
@XmlElement
public String getOrderType()
{
return OrderType;
}
public void setOrderType(String ordertype)
{
this.OrderType = ordertype;
}
}
我的UnMarshall代码(主类)
public static void main(String[] args)
{
try
{
File file = new File("C:///OrderValidation.xml");
System.out.println(1);
JAXBContext jaxbContext = JAXBContext.newInstance(Orderxml.class);
System.out.println(2);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
System.out.println(3);
Orderxml ord= (Orderxml) jaxbUnmarshaller.unmarshal(file);
System.out.println(4);
System.out.println(ord.getOrderType()+". "+ord.getProductName());
}
catch (JAXBException e)
{
System.out.println("Issue is here");
e.printStackTrace();
}
}
当我执行代码时,它会抛出null作为输出。请告诉我代码中的更改,以便检索值。提前致谢
答案 0 :(得分:2)
你JAXB POJO似乎不正确。根据您的XML结构,它应该是:
@XmlRootElement(name ="OrderValidation")
public class Orderxml
{
@XmlElement("OrderType")
private List<OrderType> orderTypes;
}
public class OrderType{
@XmlElement("Product")
private Product product;
@XmlAttribute(name="name")
private String name;
}
public class Product {
@XmlElement("Name")
private String name;
@XmlElement("ActionCode")
private String actionCode;
}
您可以使用在线工具从XML生成近似xsd,然后使用schemagen实用程序生成POJO而不是手写它。