如何使用Java中的xmlet/XsdParser验证XML是否与XSD匹配



我正在尝试验证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。如何做到这一点?

  1. 我想使用XMLET/XSDPARSER来解析我的XSD文件
  2. 我正在使用SAX PARSER来解析我的XML文件
  3. 我在网上找不到任何使用XMLET/XSDPARSER实现的好例子

如有任何帮助,我们将不胜感激。谢谢

您使用的库显然是用于分析XSD模式的库,而不是用于使用该模式进行验证的库,因此您使用的工具不对。您可以使用JAXP接口在Java中执行XSD 1.0验证(请参阅https://docs.oracle.com/javase/tutorial/jaxp/dom/validating.html),如果您想使用XSD 1.1,请下载Apache Xerces或Saxon。

最新更新