您好我刚开始学习xsd,因为我想将它与JAXB一起使用。
我想知道我可能有一个以相同元素开头的XML标记,但每次都可能有完全不同的子元素。
这是一个例子:
<service>Hotel
<request>location
<currentLongitude>100</currentLongitude>
<currentLatitude>100</currentLatitude>
</request>
</service>
例2:
<service>Hotel
<request>Price
<Single>130</Single>
<Double>140</Double>
</request>
</service>
基本上我如何在xsd中写这个“请求”被提出可以有完全不同的元素
或者,如果它适用,他们是一个更好的方法来处理这个xml然后JAXB?
由于
答案 0 :(得分:1)
您可以将request
元素定义为:
<xsd:element name="request">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
这将导致JAXB生成一个注释为:
的字段/属性@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
完整示例
<强> any.xsd 强>
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="service">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="request"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="request">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
XJC致电
xjc -d out -p forum8776746 any.xsd
<强>服务强>
package forum8776746;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"request"
})
@XmlRootElement(name = "service")
public class Service {
@XmlElement(required = true)
protected Request request;
public Request getRequest() {
return request;
}
public void setRequest(Request value) {
this.request = value;
}
}
请求强>
package forum8776746;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "request")
public class Request {
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
}
答案 1 :(得分:0)
XSD的重点是约束XML消息,以便应用程序更容易处理。我建议你重新考虑为每种类型的请求提供单独元素的方法。例如,
<service>
<hotel-location-request>
<currentLongitude>100</currentLongitude>
<currentLatitude>100</currentLatitude>
</hotel-location-request>
</service>
<service>Hotel
<hotel-price-request>
<Single>130</Single>
<Double>140</Double>
</hotel-price-request>
</service>