我试图将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次嵌套元素,并且只想映射这个嵌套元素的一个属性。我得为此创建4个类??
谢谢你的回答
发布于 2020-04-17 09:34:43
如果您想避免创建深度嵌套结构,可以始终使用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表达式来选择子元素:
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "manufacturer";
Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);https://stackoverflow.com/questions/61267626
复制相似问题