gpt4 book ai didi

java - Jackson XmlMapper 映射嵌套元素的 XML 属性

转载 作者:行者123 更新时间:2023-12-01 17:22:30 35 4
gpt4 key购买 nike

我正在尝试将 XML 解析为 Java 类,然后将其发送到前端。我正在使用 Springboot 2.2.5,Jackson 数据格式 xml 2.10.2

我有以下 XML 文件:

<root xmlsn="...">
<result status="1" outs="6" val="0" pic="7"/>
</root>

我期望前端后端做出这样的响应:

{
status: 1,
outs: 6,
val: 0
pic: 7
}

嗯,这非常简单。

让我们看看我有什么:

根元素的类:

@JacksonXmlRootElement(namespace = "...", localName = "root")
public class SetXmlResponseDto {

@JacksonXmlProperty(localName = "result")
private ResultPropertyDto result;
}

然后为结果元素 ResultPropertyDto 类:

public class ResultPropertyDto {

@JacksonXmlProperty(localName = "val", isAttribute = true)
private String value;

@JacksonXmlProperty(localName = "status", isAttribute = true)
private String status;
}

//我删除了brewity的一些代码(setter,getter)

但是结果如下:

{
result: {
status: 1,
....
}
}

最好也提及我是如何构建它的?

ObjectMapper objectMapper = new XmlMapper();
objectMapper().readValue(new URL(urlAddress), SetXmlResponseDto.class);

当然,我可以在将其发送到前端之前调用 SetXmlResponseDto.getStatus() ,输出将完全符合预期,但我想知道,有没有办法实现无需创建子类 ResultPropertyDto ??

所需的结果

假设您在 XML 中有 4 次嵌套元素,并且只想映射此嵌套元素的 1 个属性。我必须为此创建 4 个类??

谢谢各位的解答

最佳答案

如果您想避免创建深层嵌套结构,您可以随时使用 xpath .

来自提到的文档引用:

consider the following widget.xml file

<widgets>
<widget>
<manufacturer/>
<dimensions/>
</widget>

The element can be selected with the following XPath API code:

// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("/widgets.xml"));

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget";
Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

With a reference to the element, a relative XPath expression can now written to select the child element:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "manufacturer";
Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);

关于java - Jackson XmlMapper 映射嵌套元素的 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61267626/

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