繁体   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