开发者

JAXB Display XML Elements with text interspersed with sub elements

开发者 https://www.devze.com 2023-03-03 03:49 出处:网络
I want some elements to be displayed with text and also take elements to be displayed within them as specified in the desired output. How do we accomplish this using JAXB annotations?

I want some elements to be displayed with text and also take elements to be displayed within them as specified in the desired output. How do we accomplish this using JAXB annotations?

@XmlRootElement
public class Notifications{
    private String subMsg;
    private String ccNUm;
    private String bodyMsg;
    private String paymentInfo;
    private String returnStatus;
}

Desired XML Output

<notifications>
    <sub_msg>
        credit card charg开发者_如何学编程e back <creditcard_no>3646</creditcard_no>
    </sub_msg>
    <body_msg>
        Payment of <payment_amount> $12.00 </payment_amount>
        has been <return_status> Charged back </return_staus> to us
    </body_msg>
</notifications>

Regards, -Anand


I agree with skaffman, first you need to look for alternatives for this mixed-mode xml.

I wrote the beginning of a a solution, not a complete one and should be refactor to some mechanism but I am sure it will be enough understand my direction

@XmlRootElement(name="notifications")
public class Notification   {
    @XmlTransient
    public String ccNUm;
    @XmlTransient
    public String subMsg;
    @XmlAnyElement
    public List<Element> el  = Lists.newArrayList();

    public void afterUnmarshal(Unmarshaller u , Object parent) {
        for (Element e: el) {
            if ("sub_msg".equalsIgnoreCase(e.getTagName())){
                subMsg = e.getTextContent();
                Node creditCardNumberElement = e.getFirstChild().getNextSibling();
                if ("creditcard_no".equalsIgnoreCase(creditCardNumberElement.getNodeName()))
                    ccNUm = creditCardNumberElement.getTextContent(); 
            }
        } 
    }
}

Here are the tests:

private Notification tested;
private String msg = "<notifications><sub_msg>credit card charge back <creditcard_no>3646</creditcard_no></sub_msg>/notifications>";
@Before 
public void setup() throws JAXBException{
    tested = () JAXBContext.newInstance(U.class).createUnmarshaller().unmarshal(new StringReader(msg));
}
@Test
public void testSubMessage(){
    assertEquals("credit card charge back 3646",tested.subMsg);
}
@Test
public void testCreditCardNum(){
    assertEquals("3646",tested.ccNUm);
}

NOTE: This solution doesn't use the parsing benefits of jaxb beside @XmlAnyElement if this is the majority of your beans I suggest to find a better solution or a better design :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号