【问题标题】:Creating @XmlElement with same name tag 2 times创建具有相同名称标签的@XmlElement 2 次
【发布时间】:2015-03-18 08:34:53
【问题描述】:

我想解组 XML 并且 node 的元素存在于多个类文件中,我需要知道我们是否可以使用相同的名称创建 @XmlElement 标记 2 次并传递相同的节点到两个不同的班级

我有以下 XML:

<data>
    <properties>
        <id>ID123</id>
        <name>sss</name>
        <note>note</note>
    </properties>
</data>

根类文件

@XmlRootElement(name="data")
public class Data {
    prop1 prop1;
    prop2 prop2;

    @XmlElement(name="properties")
    public prop1 getProp1(){
        return this.prop1;
    }
    public void setProp1(prop1 prop1){
        this.prop1 = prop1;
    }

    @XmlElement(name="properties")
    public prop2 getProp2(){
        return this.prop2;
    }
    public void setProp2(prop2 prop2){
        this.prop2 = prop2;
    }
}

public class prop1{
    private String id;
    private String name;

    @XmlElement(name="id")
    //setters and getters for id node

    @XmlElement(name="name")
    //setters and getters for name node
}

public class prop2{
    private String note;

    @XmlElement(name="note")
    //setters and getters for note node
}

我在prop1 类中有idname,在prop2 类中有note。所有元素都在一个节点下。 我可以用 @XmlElement 标记两次同名的数据类并将同一个节点传递给两个不同的类吗?我试过了,但只能创建一个 prop1 类的实例。

也在寻找其他选项来处理这种情况

【问题讨论】:

    标签: java xml jaxb unmarshalling


    【解决方案1】:

    首先,你真的需要这样做吗?为什么你不能有一个属性类,你可以从中获取 Note 部分和 Id/Name 部分的包装器。

    一种方法是将 xml 属性映射到 xml 中,并使用编组/取消编组事件将其转换为您的 prop 类。

    public class Properties {
    @XMLElement
    String id;
    @XMLElement
    String name;
    @XMLElement
    String note;
    }
    
    public class Data {
     @XMLElement
     Properties properties;
     @XMLTransient
     Prop1 prop1
     ....
    
     void afterUnmarshal(Unmarshaller unm, Object parent) {
        prop1.id = properties.id;
        prop1.name = prperites.name;
        prop2.note = properties.note;
     };
    
     boolean beforeMarshal(Marshaller mar) {  
        prop1 = new Prop1(properties.id,properties.name);
        prop2 = new Prop2(properties.note);
     };
    }
    

    因此,您需要额外的容器(属性)来存储值,但它适用于任何 jaxb 实现。

    为了避免容器,您可以使用 XMLAdapter 和 jaxb 扩展,使用 XMLTransforamtion 从您的 xml 节点中提取必要的部分。 您可以在此处找到带有部分示例的说明:

    http://blog.bdoughan.com/2010/08/xmltransformation-going-beyond.html

    但基于 jaxb 的 eclipse 实现,需要大量代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 2021-07-10
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多