getting Dynamic attribute for element in Jaxb

狂风中的少年 提交于 2020-01-20 08:09:56

问题


I have the following XML tag with many attributes. The number/name of the attributes is not given because I am getting the XML in runtime and I just know the name of the tag. How can I use JAXB to get all the attribute as a Map<String, String>?

How can I add this to the following Java code:

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "script ")
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class SearchScriptElement
{

    @XmlAttribute(name = "script")
    private String script = "";

    public String getScript()
    {
        return name;
    }

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

XML example: I can have many attributes that aren't known in runtime:

<ScriptList>
    <script name="xxx" value="sss" id=100 >
    <script>
    <script name="xxx" value="sss" id=100 alias="sss">
    <script>
</ScriptList>

回答1:


You can do:

@XmlAnyAttribute
private Map<QName, String> attributes;

Almost the Map<String, String> that you wanted.




回答2:


Create 2 classes ScriptList and Script:

@XmlType(name = "ScriptList")
public class ScriptList {
    private Collection<Script> scripts;

    @XmlElement(name = "location")
    public Collection<Script> getSripts() {
        return scripts;
    }
}

@XmlType(name = "script")
public class Script {
    private String name;
    private String value;
    private String id;
    private String alias;

    @XmlAttribute(name="name")
    public String getName() {
        return name;
    }
    // add similar getters for value, id, alias.
    // add setters for all fields.
}

I believe, that's all. At least this can be your starting point.



来源:https://stackoverflow.com/questions/9656416/getting-dynamic-attribute-for-element-in-jaxb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!