如何通过 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。

此外,命名空间应该在包级别处理。