gpt4 book ai didi

java - 从 xml 文件检索值的 JAXB 程序

转载 作者:行者123 更新时间:2023-11-30 02:34:08 26 4
gpt4 key购买 nike

我正在尝试使用 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 作为输出。请建议我更改代码以便检索值。提前致谢

最佳答案

你们的 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,而不是手写它。

关于java - 从 xml 文件检索值的 JAXB 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43540340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com