我有以下带有许多属性的XML标记。没有给出属性的数量/名称,因为我在运行时获取XML,而我只知道标记的名称。
如何使用JAXB将所有属性作为Map<String, String>
?
如何将其添加到以下Java代码中:
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示例: 我可以有很多在运行时都不知道的属性:
<ScriptList>
<script name="xxx" value="sss" id=100 >
<script>
<script name="xxx" value="sss" id=100 alias="sss">
<script>
</ScriptList>
答案 0 :(得分:5)
你可以这样做:
@XmlAnyAttribute
private Map<QName, String> attributes;
几乎是你想要的Map<String, String>
。
答案 1 :(得分:0)
创建2个类ScriptList
和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.
}
我相信,就是这样。至少这可以是你的出发点。