gpt4 book ai didi

java - 是否可以使用 JAXB 根​​据某些属性值获取 XML 元素?

转载 作者:行者123 更新时间:2023-12-01 12:46:23 26 4
gpt4 key购买 nike

我使用 JAXB 创建了一个名为 Height.xml 的 XML 文件。结构如下所示。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<heightList>
<measurement id="5">
<height>4'4"</height>
</measurement>
<measurement id="4">
<height>4'3"</height>
</measurement>
<measurement id="3">
<height>4'2"</height>
</measurement>
<measurement id="2">
<height>4'1"</height>
</measurement>
<measurement id="1">
<height>4'0"</height>
</measurement>
</heightList>

此 XML 文件可以解码为 List<Height>如下。

JAXBContext jaxb=JAXBContext.newInstance(HeightList.class);
File file=new File("Height.xml");
List<Height> heightList = ((HeightList) jaxb.createUnmarshaller().unmarshal(file)).getList();

是否可以根据属性获取XML元素id这样就可以代替 List<Height> ,只有一个 Height 类型的对象已获取? id属性是唯一的。

<小时/>

相关类:

高度:

public final class Height implements Serializable
{
private Integer id;
private String height;
private static final long serialVersionUID = 1L;

public Height() {}

@XmlAttribute(name = "id")
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getHeight() {
return height;
}

public void setHeight(String height) {
this.height = height;
}
}

高度列表:

@XmlRootElement(name = "heightList")
@XmlAccessorType(XmlAccessType.PROPERTY)
public final class HeightList implements Serializable
{
@XmlElement(name="measurement")
private List<Height>list;
private static final long serialVersionUID = 1L;

public HeightList() {}

public HeightList(List<Height> list) {
this.list = list;
}

public List<Height> getList() {
return list;
}
}

最佳答案

您有一个列表 heightList,您可以从文档/对象树中检索它,而无需任何额外的开销 - 它是该树的一部分。部分解码尚未完成。

要找到具有特定 ID 值的高度:

Height getById( List<Height> list, Integer id ){
for( Height h: list ){
if( h.getId().equals(id) ) return h;
}
return null;
}

可能值得考虑使用 XSLT 之类的方法将 XML 文档缩减为包含单个 <mesurement> 的文档。并对其进行解码。

除非列表很长,否则可能不值得付出努力。

关于java - 是否可以使用 JAXB 根​​据某些属性值获取 XML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24662235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com