如何通过 JAXB 解组 XML,其中父节点和子节点名称相同

我之前见过这个问题,但唯一接受的答案是 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解析它?


喵喔喔
浏览 91回答 1
1回答

湖上湖

以下是如何读取该 XML 的示例:@XmlRootElement(name="Envelope", namespace="http://schemas.xmlsoap.org/soap/envelope/")class Envelope {&nbsp; &nbsp; @XmlElement(name="Body", namespace="http://schemas.xmlsoap.org/soap/envelope/")&nbsp; &nbsp; Body body;}class Body {&nbsp; &nbsp; @XmlElementWrapper(name="Features")&nbsp; &nbsp; @XmlElement(name="Features")&nbsp; &nbsp; List<Feature> features;}class Feature {&nbsp; &nbsp; @XmlElement(name="id")&nbsp; &nbsp; int id;&nbsp; &nbsp; @XmlElement(name="code")&nbsp; &nbsp; String code;&nbsp; &nbsp; @XmlElement(name="Week")&nbsp; &nbsp; String week;}String xml = "<SOAP-ENV:Envelope\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"<SOAP-ENV:Body>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; <Features>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp; <Features>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <id>213</id>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <code>232BD13</code>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Week>202020</Week>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp;</Features>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"&nbsp; &nbsp;</Features>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"</SOAP-ENV:Body>\r\n" +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"</SOAP-ENV:Envelope>";Unmarshaller unmarshaller = JAXBContext.newInstance(Envelope.class).createUnmarshaller();Envelope envelope = (Envelope) unmarshaller.unmarshal(new StringReader(xml));for (Feature f : envelope.body.features)&nbsp; &nbsp; System.out.printf("%d, %s, %s%n", f.id, f.code, f.week);输出213, 232BD13, 202020为了简单起见,上面直接使用了字段,因此您可以看到发挥作用的注释。您的实际代码应该使用 getter 和 setter。此外,命名空间可能应该在包级别处理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java