java xml注释获取具有命名空间的字段,<aaa:bbb>值</aaa:bbb>

2022-01-19 00:00:00 xml java jaxb

我正在处理一个没有架构的项目,我必须手动解析 xml 响应.我的问题是我无法使用 xml 注释获得一些价值.

I'm working on a project that has no schema and I have to parsing the xml response manually. My problem is i can't get some value using the xml annotation.

例如,xml是这样的:

For example , the xml is like:

<?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> ?太感谢了!!!

I can get the action and the response, but can't get the numhits in the responsedata, Can anyone tell me how to handle the <autn:numhits> using annotation? Too much Thanks !!!

另一个问题是:我在响应数据中有多个 <autn:numhits>....我怎样才能获得 Java 代码中的所有值.em>--> 我解决了这个多个相同的标签,只要设置List,注解就会自动生成列表

Another issue is : I have multi <autn:numhits> in the responsedata....how can i get all the value in the Java code. --> I solve this multi same tags, just set List and the annotation will automatically generate the list

推荐答案

事实是 autn - 只是前缀,而不是命名空间.为了正确处理 XML 文档,必须声明命名空间.

The fact is autn - is only prefix, not namespace. For correct processing of the XML document, namespace must be declared.

正确的命名空间声明:

<?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 代码.

And finnaly advice for you. If you have a xsd scheme for this xml document, use the XJC utilit for java code generation.

http://docs.oracle.com/javaee/5/教程/doc/bnbah.html

相关文章