我正在尝试验证XML
是否符合XSD
。为了实现这一点,我使用了xmlet/XsdParser,但除了GitHub页面之外,我找不到任何好的例子。
在自述文档中,他们只提供了如何将XSD
转换为相应的Java objects
,但没有显示如何验证XML是否与XSD匹配。
以下是我读取XSD并创建Java对象的代码:
public class XSDParser {
public static void main(String[] args) throws URISyntaxException {
String xsdPath = Paths.get(XSDParser.class.getClassLoader().getResource("test.xsd").toURI()).toFile().getAbsolutePath();
String filePath = Path.of(xsdPath).toString();
XsdParser parserInstance = new XsdParser(filePath);
System.out.println(filePath);
Stream<XsdElement> elementsStream = parserInstance.getResultXsdElements();
Stream<XsdSchema> schemasStream = parserInstance.getResultXsdSchemas();
}
}
此代码读取XSD文件并创建元素的Stream。现在,我还添加了以下几行代码,这些代码将读取XML文件并创建流:
String absolutePath = Paths.get(ApplicationMain.class.getClassLoader().getResource("inputXML.xml").toURI()).toFile()
.getAbsolutePath();
String path = Path.of(absolutePath).toString();
File xml = new File(path);
InputStream stream = new FileInputStream(xml);
现在,我想知道我的XML是否符合我已经读取和存储的XSD。如何做到这一点?
- 我想使用
XMLET/XSDPARSER
来解析我的XSD文件 - 我正在使用
SAX PARSER
来解析我的XML文件 - 我在网上找不到任何使用
XMLET/XSDPARSER
实现的好例子
如有任何帮助,我们将不胜感激。谢谢
您使用的库显然是用于分析XSD模式的库,而不是用于使用该模式进行验证的库,因此您使用的工具不对。您可以使用JAXP接口在Java中执行XSD 1.0验证(请参阅https://docs.oracle.com/javase/tutorial/jaxp/dom/validating.html),如果您想使用XSD 1.1,请下载Apache Xerces或Saxon。