[英]Jackson XmlMapper map XML attribute of nested element
我正在嘗試將 XML 解析為 Java class 然后將其發送到前端。 我正在使用 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
}
嗯,這非常容易。
讓我們看看,我有什么:
Class 為根元素:
@JacksonXmlRootElement(namespace = "...", localName = "root")
public class SetXmlResponseDto {
@JacksonXmlProperty(localName = "result")
private ResultPropertyDto result;
}
然后是結果元素 ResultPropertyDto 的 class:
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()
並且 output 將完全符合預期,但我想知道,有沒有辦法在不創建子類ResultPropertyDto
的情況下實現所需的結果?
假設您在 XML 中有 4 次嵌套元素,並且想要 map 僅此嵌套元素的 1 個屬性。 我必須為此創建4個類?
感謝您的回答
如果您想避免創建深層嵌套結構,您始終可以使用xpath 。
從提到的文檔參考:
考慮以下 widget.xml 文件
<widgets>
<widget>
<manufacturer/>
<dimensions/>
</widget>
可以使用以下 XPath API 代碼選擇元素:
// 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);
通過引用該元素,現在可以將相對 XPath 表達式寫入 select 子元素:
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "manufacturer";
Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.