[英]Getting multiple XML elements with the same name JAXB
可能是一個愚蠢的問題,但我被困住了。
我嘗試解析從REST服務檢索到的巨大xml文檔。 我感興趣的都是抽象部分。
<article article-type="research-article">
<front>
<article-meta>
<abstract></abstract>
<abstract abstract-type="summary"></abstract>
</article-meta>
</front>
</article>
在我的上課時,我執行以下操作:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Front {
@XmlElementWrapper(name = "article-meta")
@XmlElement(name="abstract")
private List<AuthorSummary> authorSummaries = new ArrayList<AuthorSummary>();
/** Getter and Setter **/
}
可悲的是,我只得到了第一個摘要,但那里也有內容。 您可以在下面看到我的AuthorSummary類。
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class AuthorSummary {
@XmlElement(name = "title")
private String title;
@XmlElement(name = "p")
private String content;
@XmlAttribute(name = "abstract-type")
private String abstractType;
/** Getter and Setter **/
}
因此,我很困惑,希望得到任何提示。
非常感謝你
我有一個解決方案,但是它根本沒有使用jaxb甚至數據綁定。 因此,如果您堅持使用數據綁定,我將刪除答案。 否則,我希望您指向數據投影 (公開:我隸屬於該項目)而不是數據綁定:
public class ReadElementsWithSameName {
public interface Article {
@XBRead("./@article-type")
String getType();
@XBRead("./front/article-meta/abstract")
List<String> getAllAbstracts();
@XBRead("./front/article-meta/abstract[@abstract-type='summary']")
String getSummary();
}
// Configure the underlying document builder to not load the (nonexisting) DTD
private static final XMLFactoriesConfig nonValidatingConfig = new DefaultXMLFactoriesConfig() {
@Override
public DocumentBuilderFactory createDocumentBuilderFactory() {
DocumentBuilderFactory factory = super.createDocumentBuilderFactory();
try {
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
return factory;
}
};
public static void main(String... args) throws IOException {
List<Article> articles = new XBProjector(nonValidatingConfig).io().url("res://data.xml").evalXPath("/article").asListOf(Article.class);
for (Article article:articles) {
System.out.println(article.getType());
System.out.println(article.getSummary());
System.out.println(article.getAllAbstracts());
}
}
}
無需使用Java類來反映XML結構,只需將Java API定義為具有所需訪問器(和設置器)的“投影接口”。 之后,讓投影框架負責讀取和寫入對DOM的更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.