亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 JAXB 解組 XML,其中父節點和子節點名稱相同

如何通過 JAXB 解組 XML,其中父節點和子節點名稱相同

喵喔喔 2023-07-13 15:52:02
我之前見過這個問題,但唯一接受的答案是 C#。您可以讓我知道可以通過 Java 做到這一點。這是場景:-<SOAP-ENV:Envelopexmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body>    <Features>        <Features>          <id>213</id>          <code>232BD13</code>          <Week>202020</Week>       </Features>   </Features></SOAP-ENV:Body>在上面的 JAXB XML 解析中,我遇到了幾個問題。我不知道如何忽略屬性“xmlns:SOAP-ENV =“http://schemas.xmlsoap.org/soap/envelope/””特征節點作為父節點和子節點。如何通過JAXB解析它?
查看完整描述

1 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

以下是如何讀取該 XML 的示例:


@XmlRootElement(name="Envelope", namespace="http://schemas.xmlsoap.org/soap/envelope/")

class Envelope {

    @XmlElement(name="Body", namespace="http://schemas.xmlsoap.org/soap/envelope/")

    Body body;

}

class Body {

    @XmlElementWrapper(name="Features")

    @XmlElement(name="Features")

    List<Feature> features;

}

class Feature {

    @XmlElement(name="id")

    int id;

    @XmlElement(name="code")

    String code;

    @XmlElement(name="Week")

    String week;

}

String xml = "<SOAP-ENV:Envelope\r\n" + 

             "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n" + 

             "<SOAP-ENV:Body>\r\n" + 

             "    <Features>\r\n" + 

             "        <Features>\r\n" + 

             "          <id>213</id>\r\n" + 

             "          <code>232BD13</code>\r\n" + 

             "          <Week>202020</Week>\r\n" + 

             "       </Features>\r\n" + 

             "   </Features>\r\n" + 

             "</SOAP-ENV:Body>\r\n" + 

             "</SOAP-ENV:Envelope>";

Unmarshaller unmarshaller = JAXBContext.newInstance(Envelope.class).createUnmarshaller();

Envelope envelope = (Envelope) unmarshaller.unmarshal(new StringReader(xml));

for (Feature f : envelope.body.features)

    System.out.printf("%d, %s, %s%n", f.id, f.code, f.week);

輸出


213, 232BD13, 202020

為了簡單起見,上面直接使用了字段,因此您可以看到發揮作用的注釋。您的實際代碼應該使用 getter 和 setter。


此外,命名空間可能應該在包級別處理。


查看完整回答
反對 回復 2023-07-13
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號