我试图使用XML并以一种简单的方式访问所有字段和数据,因此,我决定使用JaxB,但是我不知道如何为对象创建所有类,因此我手动进行了尝试。

@XmlRootElement(name = "Response")
public class Response {

    @XmlElement(ns = "SignatureValue")
    String signatureValue;

}


但是我在@XmlElement上收到一个错误,说该位置不允许使用注释...

我检查了其他帖子,如果我有类似Hellw的内容,但它们工作得很好,但不适用于更复杂的格式,我的第一部分的示例是这样的

<?xml version="1.0" encoding="UTF-8"?><DTE xsi:noNamespaceSchemaLocation="http://www.myurl/.xsd" xmlns:gs1="urn:ean.ucc:pay:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">




任何想法如何做到这一切?

提前致谢

编辑:

我忘了说,XML实际上是包含整个XML的字符串。

最佳答案

@XmlElement注释在字段上有效。如果您具有相应的属性,则应使用@XmlAccessorType(XmlAccessType.FIELD)注释该类,以避免重复的映射异常。

Java模型

注释字段

@XmlRootElement(name = "Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

    @XmlElement(name = "SignatureValue")
    String signatureValue;

    public String getSignatureValue() {
        return signatureValue;
    }

    public void setSignatureValue(String signatureValue) {
        this.signatureValue = signatureValue;
    }

}


注释属性

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "Response")
public class Response {

    String signatureValue;

    @XmlElement(name = "SignatureValue")
    public String getSignatureValue() {
        return signatureValue;
    }

    public void setSignatureValue(String signatureValue) {
        this.signatureValue = signatureValue;
    }

}


欲获得更多信息


http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html


示范代码

以下是一些演示代码,该代码读取/写入与您的Response类相对应的XML。

演示版

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum19713886/input.xml");
        Response response = (Response) unmarshaller.unmarshal(xml);

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

}


input.xml /输出

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <SignatureValue>Hello World</SignatureValue>
</Response>

10-01 09:36
查看更多