我需要构建一个解析器来解析XML
文件到一个Java
目的。
我用Jackson
为此,请按照中提供的步骤操作THIS教程。
在教程中有一节'操作 XML 中的嵌套元素和列表'。我遵循了它,但不幸的是我无法获得所有所需元素的所需输出 - 我想输出所有作者的第一个和最后一个。我只为我的最后一位作者得到它XML
-这样的文件:
[{nameList={person={first=Karl, last=S}}}]
My XML
文件看起来像这样。
<sources>
<Doi>123456789</Doi>
<Title>Title</Title>
<author>
<editor>
<nameList>
<person>
<first>Peter</first>
<last>Parker</last>
</person>
</nameList>
</editor>
</author>
<Source>
<SourceType>Book</SourceType>
<ShortTitle>Book Title</ShortTitle>
<Author>
<Editor>
<NameList />
</Editor>
</Author>
</Source>
<author>
<bookAuthor>
<nameList>
<person>
<first>Karl</first>
<last>S</last>
</person>
</nameList>
</bookAuthor>
</author>
<Source>
<SourceType>Journal</SourceType>
<ShortTitle>ABC Journal</ShortTitle>
</Source>
</sources>
如何反序列化整个 XML 文件?
我的代码如下所示:
MyClass.java
private static void jacksonXmlFileToObject() throws IOException {
System.out.println("jacksonXmlFileToObject");
InputStream xmlFile = Publication.class.getClassLoader().getResourceAsStream("test.xml");
ObjectMapper mapper = new XmlMapper();
// Configure
mapper
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
Sources deserializedData = mapper.readValue(xmlFile, Sources.class);
System.out.println(deserializedData);
} catch (IOException e) {
e.printStackTrace();
}
}
来源.java
@EqualsAndHashCode
@JacksonXmlRootElement(localName = "sources") public class Sources {
@JacksonXmlElementWrapper(localName = "author")
@Getter
@Setter
private Object[] author;
@Override
public String toString() {
return Arrays.toString(author);
}
public Sources() {
}
}
如果能得到一些帮助,我会非常高兴。
谢谢你!
Use the JsonMerge
注解。
我自己最近也遇到了类似的问题,发现注释@JsonMerge
解决了问题。
我稍微简化了 XML:
<sources>
<author>
<name>Jack</name>
</author>
<source>
<type>Book</type>
</source>
<author>
<name>Jill</name>
</author>
<source>
<type>Journal</type>
</source>
</sources>
随着班级Author
and Source
class Author {
String name;
}
class Source {
String type;
}
The Sources
类如下所示:
class Sources {
// We prevent each <author> tag to be wrapped in an <authors> container tag
@JacksonXmlElementWrapper(useWrapping = false)
// Each element is <author> and not <authors> (and we named our field 'authors')
@JacksonXmlProperty(localName = "author")
// This is the property which solves your problem. It causes non-subsequent elements with the
// same name to be merged into the existing list
@JsonMerge
private List<Author> authors;
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "source")
@JsonMerge
private List<Source> sources;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)