gpt4 book ai didi

java - Jackson XmlMapper 从子元素映射

转载 作者:行者123 更新时间:2023-12-02 03:27:28 29 4
gpt4 key购买 nike

我正在使用 Jackson XmlMapper 将 xml 映射到 POJO,但遇到以下问题:

我的 XML 看起来像这样(不是原始的,只是一个示例):

<?xml version="1.0" encoding="UTF-8"?>
<result>
<pojo>
<name>test</name>
</pojo>
</result>

问题是,我不想解析“结果”对象。我不想将 pojo 解析为自己的对象。我可以使用 XmlMapper 执行此操作吗?

谢谢!

阿图尔

最佳答案

您可以做到,但您必须编写一些样板代码。您必须创建一个 XMLStreamReader 实例才能对 xml 输入进行自定义读取。 next() 方法允许转到阅读器的下一个解析事件。这是一个与读者的内部规则相关的相当棘手的 method() 。因此,请阅读文档以了解特殊性:

来自 Javadoc:
int javax.xml.stream.XMLStreamReader.next() 抛出 XMLStreamException

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks. If the property javax.xml.stream.isCoalescing is set to true element content must be coalesced and only one CHARACTERS event must be returned for contiguous element content or CDATA Sections. By default entity references must be expanded and reported transparently to the application. An exception will be thrown if an entity reference cannot be expanded. If element content is empty (i.e. content is "") then no CHARACTERS event will be reported.

Given the following XML: content textHello</greeting>]]>other content The behavior of calling next() when being on foo will be: 1- the comment (COMMENT) 2- then the characters section (CHARACTERS) 3- then the CDATA section (another CHARACTERS) 4- then the next characters section (another CHARACTERS) 5- then the END_ELEMENT

NOTE: empty element (such as ) will be reported with two separate events: START_ELEMENT, END_ELEMENT - This preserves parsing equivalency of empty element to . This method will throw an IllegalStateException if it is called after hasNext() returns false.

Returns: the integer code corresponding to the current parse event

让我说明一下进行单元测试的方法:

@Test   
public void mapXmlToPojo() throws Exception {
XMLInputFactory factory = XMLInputFactory2.newFactory();
InputStream inputFile = MapXmlToPojo.class.getResourceAsStream("pojo.xml");
XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(inputFile);
XmlMapper xmlMapper = new XmlMapper();
xmlStreamReader.next();
xmlStreamReader.next();
Pojo pojo = xmlMapper.readValue(xmlStreamReader, Pojo.class);
Assert.assertEquals("test", pojo.getName());
}

关于java - Jackson XmlMapper 从子元素映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38618753/

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