我有一个输出类似
的提供者<Result rawScore="623">
<Target>http://myUrl.com/test1</Target>
<Domain name="myUrl.search.com" />
<Property name="Language">en</Property>
<Property name="Teaser">This is the description</Property>
<Property name="LVCategory">Help</Property>
<Property name="Title">ProductTitle</Property>
<Property name="Last Modified">2012-04-06T21:44:11Z</Property>
</Result>
我正在尝试创建一个xsd来利用jaxb,但我不确定如何处理Property属性多次出现但不在列表中,因此序列将不起作用。有什么想法吗?
答案 0 :(得分:3)
这是一个完整的XML Schema,并编译为Java代码
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="2.0">
<xsd:element name="Result" type="ResultType"/>
<xsd:complexType name="ResultType">
<xsd:sequence>
<xsd:element name="Target" type="xsd:string"/>
<xsd:element name="Domain" type="xsd:string"/>
<xsd:element name="Property" type="PropertyType"
minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="rawScore" type="xsd:int"/>
<!-- xsd:integer => BigDecimal/PITA -->
</xsd:complexType>
<!-- I prefer explicit types to avoid nested class definitions -->
<xsd:complexType name="PropertyType">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="name" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:schema>
几行Java代码:
JAXBContext jc = JAXBContext.newInstance( PACKAGE );
Unmarshaller m = jc.createUnmarshaller();
try {
File source = new File( XMLIN );
JAXBElement<ResultType> jbe = (JAXBElement<ResultType>)m.unmarshal( source );
ResultType result = (ResultType)jbe.getValue();
} catch( Exception e ){
}
答案 1 :(得分:2)
您可以执行以下操作:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="Result">
<complexType>
<sequence>
...
<element name="Property" minOccurs="0" maxOccurs="unbounded">
<complexType>
<simpleContent>
<extension base="string">
<attribute name="name" type="string"/>
</extension>
</simpleContent>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
请注意有关XML Schema的以下内容:
Property
元素具有属性maxOccurs="unbounded"
。这表明它是一个重复元素。Property
元素是一个内容简单的复杂类型。这意味着它可以具有文本值和XML属性。答案 2 :(得分:0)
使用以下内容声明Result
的类型:
<xsd:complexType name="ResultType">
<xsd:sequence>
<xsd:element ref="Target"/>
<xsd:element ref="Domain"/>
<xsd:element ref="Property"
minOccurs="0"
maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="rawScore" type="xsd:integer"/>
</xsd:complexType>
了解元素和属性之间的区别,好吗?