简体   繁体   English

具有相同类型但名称不同的多个元素?

[英]Multiple elements with the same type but different name?

Is there any way to assign different names to the same type when using @XmlElements ? 使用@XmlElements时,是否可以将不同的名称分配给同一类型? I started off with just using @XmlElement . 我从仅使用@XmlElement Did some reading and found @XmlElementWrapper and the @XmlElements but still have not been able to get my desired output. 做一些阅读,发现@XmlElementWrapper@XmlElements但是仍然无法获得我想要的输出。 I realize that I could just make different data types for the 2 but it would be sweet if I could just do this with annotations. 我意识到我可以为2设置不同的数据类型,但是如果我可以使用批注来做到这一点,那将很不错。

Current Iteration: 当前迭代:

@XmlRootElement(name = "Root")
public class XmlTest {

    @XmlElementWrapper(name="ContactInformation")
    @XmlElements({
            @XmlElement(name="Name"),
            @XmlElement(name="LogicalOwner")
    })
    public List<String> contactInformation;
    ...
        contactInformation = new ArrayList<>();
        contactInformation.add("should be inside name");
        contactInformation.add("should be insde of owner");
    ...

Current Output: 电流输出:

<Root>
    <ContactInformation>
        <LogicalOwner>should be inside name</LogicalOwner>
        <LogicalOwner>should be insde of owner</LogicalOwner>
    </ContactInformation>
</Root>

Desired Output: 所需输出:

<Root>
    <ContactInformation>
        <Name>should be inside name</Name>
        <LogicalOwner>should be insde of owner</LogicalOwner>
    </ContactInformation>
</Root>

You could try making a class that stores the fields in them, and then serialize that class. 您可以尝试创建一个将字段存储在其中的类,然后序列化该类。

@XmlRootElemnt(name="root")
Class ContactInformation{

    private String name;

    @XmlElement(name="Name")
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

I'm used to using Gson.toJson(), so I'm not much help on serializing to XML; 我习惯于使用Gson.toJson(),因此在序列化到XML方面没有太多帮助; hopefully this points you in the right direction though. 希望这会为您指明正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM