Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

java xml annotation get field with namespace, <aaa:bbb>value</aaa:bbb>

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.

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>

And the java class is :

@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;
}

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 !!!

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Right namespace declaration:

<?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>

You also need to change the annotation:

@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;
}

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/tutorial/doc/bnbah.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...