我正在开发一个没有架构的项目,我必须手动解析 xml 响应。 我的问题是我无法使用 xml 注释获取一些值。
例如,xml如下:
<?xml version='1.0' encoding='UTF-8' ?>
<autnresponse>
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>7</autn:numhits>
</responsedata>
</autnresponse>
Java 类是:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "autnresponse")
public class AutonomyResponse {
private String action;
private String response;
private ResponseData responsedata;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "responsedata")
public class ResponseData {
@XmlElement(name = "numhits",namespace = "autn")
private String numhits;
@XmlElement(name = "totalhits")
private String totalhits;
}
我可以获取操作和响应,但无法获取响应数据中的 numhits,
谁能告诉我如何处理<autn:numhits>
使用注释?
太感谢了!!!
另一个问题是:我有多个 <autn:numhits>
在响应数据中......我怎样才能获得Java代码中的所有值。
--> 我解决了这个多相同标签的问题,只需设置List,注释就会自动生成列表
最佳答案
事实是autn - 只是前缀,而不是命名空间。为了正确处理 XML 文档,必须声明命名空间。
正确的命名空间声明:
<?xml version='1.0' encoding='UTF-8' ?>
<autnresponse xmlns:autn="http://namespace.here">
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>7</autn:numhits>
</responsedata>
</autnresponse>
您还需要更改注释:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "responsedata")
public class ResponseData {
@XmlElement(name = "numhits",namespace = "http://namespace.here")
private String numhits;
@XmlElement(name = "totalhits")
private String totalhits;
}
最后给你一些建议。如果您有此 xml 文档的 xsd 方案,请使用 XJC 实用程序进行 java 代码生成。
关于java xml注释获取带有命名空间的字段,<aaa :bbb>value</aaa:bbb>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062536/