2013-02-01 73 views
1

我想传入的XML绑定到一个java类型JAXB XSD元素(基本)

<?xml version="1.0" encoding="UTF-8"?> 
<apiKeys uri="http://api-keys"> 
<apiKey uri="http://api-keys/1933"/> 
<apiKey uri="http://api-keys/19334"/> 
</apiKeys> 

我希望用JAXB,所以我定义了一个XSD。我的XSD不正确,创建的对象在创建时是空的。

我的XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<xsd:element name="apiKeys" type="ApiKeysResponseInfo2" /> 

<xsd:complexType name="ApiKeysResponseInfo2"> 
<xsd:sequence> 
<xsd:element name="uri" type="xsd:anyURI" minOccurs="1" maxOccurs="1"> 
</xsd:element> 
<xsd:element name="apiKey" type="xsd:anyURI" minOccurs="1" maxOccurs="unbounded"> 
</xsd:element> 
</xsd:sequence> 
</xsd:complexType> 
</xsd:schema> 

显然,我的元素定义是错误的。任何帮助非常感谢。谢谢。

回答

1

我希望使用JAXB,所以我定义了一个XSD。

JAXB不需要XML模式。我们将它设计为从Java对象开始,添加了从XML模式生成注释模型的功能,作为便利机制。


我想传入的XML绑定到一个java类型

你可以使用下面的对象模型:

ApiKeys

import java.util.List; 
import javax.xml.bind.annotation.*; 

@XmlRootElement 
public class ApiKeys { 

    private String uri; 
    private List<ApiKey> apiKey; 

    @XmlAttribute 
    public String getUri() { 
     return uri; 
    } 

    public void setUri(String uri) { 
     this.uri = uri; 
    } 

    public List<ApiKey> getApiKey() { 
     return apiKey; 
    } 

    public void setApiKey(List<ApiKey> apiKey) { 
     this.apiKey = apiKey; 
    } 

} 

ApiKey

import javax.xml.bind.annotation.XmlAttribute; 

public class ApiKey { 

    private String uri; 

    @XmlAttribute 
    public String getUri() { 
     return uri; 
    } 

    public void setUri(String uri) { 
     this.uri = uri; 
    } 

} 

演示

import java.io.File; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(ApiKeys.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     File xml = new File("src/forum14643483/input.xml"); 
     ApiKeys apiKeys = (ApiKeys) unmarshaller.unmarshal(xml); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(apiKeys, System.out); 
    } 

} 
+1

佑,感谢为布莱斯 - 我给它一个去。我的动机实际上是与Json合作,所以我真正想要的就是Jaxb对象,并且不会维护XSD。 – Damo

+0

我目前的Jaxb物体看起来和你的一样,但是我会咀嚼几件东西并重新测试。我不明白的(翻译)部分与有关 - 但是如果其中包含类似 http:// api-keys/1933“ - 我可以看到它是如何映射的。 – Damo

+0

@Damo - “翻译”部分是否指JSON? –