I have the following xsd
file:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="city"/>
<xs:element name="temperature">
<xs:complexType>
<xs:sequence>
<xs:element name="value">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:byte">
<xs:attribute type="xs:string" name="unit"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element type="xs:dateTime" name="measured_at_ts"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
And xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<city>Copenhagen</city>
<temperature>
<value unit="celsius">27</value>
</temperature>
<measured_at_ts>2020-08-01T18:00:00</measured_at_ts>
</data
When I try to execute the following code:
public static void main(String[] args) {
System.out.println(XmlHandler.isXmlValid("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<data>" +
" <city>Copenhagen</city>" +
" <temperature>" +
" <value unit=\"celsius\">27</value>" +
" </temperature>" +
" <measured_at_ts>2020-08-01T18:00:00</measured_at_ts>" +
"</data>"));
private static boolean isXmlValid(String xml) {
boolean xmlValid = true;
try {
validate(xml);
} catch (SAXException | IOException | ParserConfigurationException e) {
xmlValid = false;
e.printStackTrace();
}
return xmlValid;
}
private static void validate(String xml) throws SAXException, ParserConfigurationException, IOException {
final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final Document document = builder.parse(new InputSource(new StringReader(xml)));
final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final String s = XmlHandler.class.getResource("/").getPath() + "weather.xsd";
factory.newSchema(new File(s)).newValidator().validate(new DOMSource(document));
}
I get org.xml.sax.SAXParseException; cvc-elt.1: Cannot find the declaration of element 'data'
.
I have tried boiling down the example to these:
xsd
:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="data">
</xs:element>
</xs:schema>
xml
:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><data></data>
and still get the same result.
Any pointers as to what causes the aforementioned error would be appreciated!