如果使用两次,@ xmlVariableNode将忽略第二个属性

时间:2016-02-10 14:18:41

标签: java xml jaxb pojo moxy

我必须创建POJO,以便我可以使用JAXB为以下XML 生成XML(只是一个示例,因为子元素可能超过40)

这里需要注意的重要一点是,我不能将这些元素声明为POJO中的属性,因为我不知道元素名称。

<User>
    <FirstName>Mahendra</FirstName>
    <MiddleName>Singh</MiddleName>
    <LastName>Dhoni</LastName>
    <Organization>
         <Name>Electronics</Name>
         <id>elc001</id>
    </Organization>
    <Manager>
         <Name>Sourabh</Name>
         <id>emp_001</id>
    </Manager>
</User>

我为上面的XML创建了POJO:

Fields1.java :仅适用于具有值的元素。

public class Fields1 
{
    @XmlTransient
    public String fieldName1;

    @XmlValue
    public String value;

    //  getter,setter
}

Fields2.java :适用于包含子元素的元素。

public class Fields2 
{
    @XmlTransient
    public String fieldName2;

    @XmlElement(name="NAME")
    public String name;

    @XmlElement(name="ID")
    public String id;

    //  getter,setter
}

User.java :根元素类

public class User
{

    @XmlVariableNode("fieldName1")
    public List<Fields1> fields1;

    @XmlVariableNode("fieldName2")
    public List<Fields2> fields2;

    //  getter, setter
}

这里,@ XmlVariableNode帮助我动态生成元素名称。
但是,如果只有一个属性,它只能正常工作 2.如果,有两个属性,那么它只适用于第一个属性而忽略下一个属性。

1 个答案:

答案 0 :(得分:0)

AFAIK, multiple =If($B2<>"",IF(YEAR($B2)=C$1,"Yes","No"),"")s in the same class are not possible. EclipseLink's documentation states:

Since this [@XmlVariableNode] makes use of the any logic during unmarshal and MOXy only handles one Any mapping on a class if a class makes use of the XmlVariableNode annotation then that class can not have XmlAnyElement annotations or any other variables that would cause AnyObject or AnyCollection mappings to be created.

(Source: EclipseLink/DesignDocs/406697)

You might be able to solve your problem by using nested @XmlVariableNodes:

@XmlVariableNode
public class TopLevelField {

    @XmlTransient
    public String fieldName;

    @XmlVariableNode("fieldName")
    public List<NestedField> fields;

    // ...
}
public class NestedField {

    @XmlTransient
    public String fieldName;

    @XmlValue
    public String value;

    // ...
}