toy
toy

Reputation: 12141

How to do partial parse xml in JAXB with validation?

I have a big XML file which I want to validation against an XSD. But from the big xml file I only want just one element

This is my example XML

<Something>
  <Element1>element</Element1>
  <IDontWantThis>element</IDontWantThis>
<Something>

And this is my POJO so I didn't include IDontWantThis

@XmlRootElement(name = "Something")
@XmlAccessorType(XmlAccessType.FIELD)
public class Something {

    @XmlElement(name = "Element1")
    private String element1;

}

And this is how I parse my XML

        StreamSource source = new StreamSource(filePath);

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(XSD));

        Unmarshaller u = JAXBContext.newInstance(Something.class).createUnmarshaller();
        u.setSchema(schema);
        u.setEventHandler(new MyValidationEventHandler());
        Products products = u.unmarshal(source, Something.class).getValue();

But I got this error when I run my application

unexpected element (uri:"urn:blah", local:"IDontWantThis"). Expected elements are <{urn:blah}Element1>,<{urn:blah}Element1>

How do I just parse partial element, because my xml is quite big and contains a lot of elements I don't really need to use.

Upvotes: 2

Views: 1185

Answers (1)

bdoughan
bdoughan

Reputation: 148987

MyValidationEventHandler is a class you have written to custom hand errors. If you want to ignore an error you just need to put the logic there.

Upvotes: 1

Related Questions