java - 从 xsd 文件生成的 JAXB 类
问题描述
我有一个 xsd 文件,它使用 xjc / JAXB 生成类。
现在我想使用方法getOwne
r(附加函数),并从这个对象中获取所有者的名称。
这个方法返回一个对象类而不是客户类的主要问题。有没有办法做到这一点?
注意:这是一个属性引用
谢谢!
这是我尝试过的:
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Statement.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/Data.xml");
Statement items = (Statement)unmarshaller.unmarshal(xml);
List<Order> orders = items.getOrders().getOrder();
for(Order order : orders) {
System.out.println(order.getOwner());
}
}
数据.xml:
<statement>
<customer number="E1" name="Tom" type="normal"/>
<customer number="E2" name="Tomer" type="normal"/>
<orders count="200">
<!--1 or more repetitions:-->
<order number="string" owner="E1" total="1000.00"/>
<order number="string2" owner="E2" total="1020.00"/>
</orders>
</statement>
架构.xsd:
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.java2s.com/statement"
xmlns="http://www.java2s.com/statement">
<xs:element name="statement">
<xs:complexType>
<xs:sequence>
<xs:element ref="customer" />
<xs:element ref="orders" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="customer">
<xs:complexType>
<xs:sequence />
<xs:attribute name="number" type="xs:ID" />
<xs:attribute name="name" type="xs:string" />
<xs:attribute name="type" type="xs:string"
use="optional" default="normal" />
</xs:complexType>
</xs:element>
<xs:element name="orders">
<xs:complexType>
<xs:sequence>
<xs:element ref="order" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="count" type="xs:nonNegativeInteger" />
</xs:complexType>
</xs:element>
<xs:element name="order">
<xs:complexType>
<xs:sequence>
</xs:sequence>
<xs:attribute name="number" type="xs:ID" />
<xs:attribute name="owner" type="xs:IDREF" />
<xs:attribute name="total" type="xs:decimal" />
</xs:complexType>
</xs:element>
</xs:schema>
Order.java 中的信息:
@XmlAttribute(name = "owner")
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object owner;
...
public Object getOwner() {
return owner;
}
解决方案
通过改变:
<xs:attribute name="owner" type="xs:IDREF" />
至:
<xs:attribute name="owner" type="xs:IDREF" >
<xs:annotation>
<xs:appinfo>
<jaxb:property>
<jaxb:baseType name="Customer" />
</jaxb:property>
</xs:appinfo>
</xs:annotation>
</xs:attribute>
和
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
至:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0" >
感谢 Markus 将我转发到正确的位置。
更多信息:自定义 JAXB 绑定
推荐阅读
- swift - Xcode 显示冲突的约束
- c# - 如何让一个对象始终在另一个对象前面?
- exist-db - 当前应用程序之外的 eXistDB HTML 模板文件
- python - 我无法抓取数据
- c# - 使用 MemSql for c# application 进行选择查询的慢查询执行
- angular - 具有工厂功能的角度自定义模块不起作用
- azure-pipelines - Azure Pipelines YAML - dotnet nuget push 失败并出现意外令牌错误
- wpf - 绑定到 ObservableCollection 中的元素
- powershell - 从 Powershell 批量删除 Azure Cosmos Db
- css - 如何使用 CSS 和 React 向元素添加溢出省略号?