Reputation: 4719
I have seen this question was asked before but the only accepted answer was by C#. You could please let me know can do it by Java. Here is the scenario:-
<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>
In the above XML parsing by JAXB, I have couple of problems.
I don't know how to ignore the attribute "xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/""
Features node is as parent and child. How to parse it by JAXB?
Upvotes: 0
Views: 334
Reputation: 159175
Here is example of how to read that 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);
Output
213, 232BD13, 202020
The above is using fields directly to keep it simple, so you can see the annotations that does the magic. Your real code should use getters and setters.
Also, namespaces should probably be handled at the package-level.
Upvotes: 1