簡體   English   中英

如何在父節點和子節點名稱相同的情況下通過JAXB解組XML

[英]How to Unmarshaller XML by JAXB where parent and child node as same name

我已經看到過有人問過這個問題,但是唯一接受的答案是C#。 您可以讓我知道Java可以做到。 這是場景:-

<SOAP-ENV:Envelope
xmlns: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解析中,我遇到了兩個問題。

  1. 我不知道如何忽略屬性“ xmlns:SOAP-ENV =“ http://schemas.xmlsoap.org/soap/envelope/”“

  2. “功能”節點作為父級和子級。 如何通過JAXB解析?

這是如何讀取該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。

同樣,名稱空間可能應該在程序包級別進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM