简体   繁体   English

如何在没有本地XSD文件的情况下根据XML模式验证XML?

[英]How to validate XML against its XML Schema without local XSD file?

This is my XML: 这是我的XML:

<?xml version="1.0"?>
<root xmlns="http://example.com/first-schema.xsd"
  xmlns:f="http://example.com/second-schema.xsd">
  <f:foo>test</f:foo>
</root>

Now I want to validate whether this XML is XMLSchema-valid. 现在,我要验证此XML是否为XMLSchema有效。 I don't have these first-schema.xsd and second-schema.xsd files locally. 我在本地没有这些first-schema.xsdsecond-schema.xsd文件。 Moreover, I don't know anything about them. 而且,我对他们一无所知。 I just want to make sure that my XML document is valid against its schemas. 我只想确保我的XML文档对其架构有效。 Is it possible to do in Java? 可以用Java做吗?

You can use the javax.xml.validation APIs for this. 您可以为此使用javax.xml.validation API。

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
URL schemaURL = // The URL to your XML Schema; 
Schema schema = sf.newSchema(schemaURL); 
Validator validator = schema.newValidator();
DOMSource source = new DOMSource(xmlDOM);
validator.validate(source);

The example below demonstrates how to validate a JAXB object model against a schema, but you'll see it's easy to replace the JAXBSource with a DOMSource for DOM: 下面的示例演示了如何针对模式验证JAXB对象模型,但是您会发现用DOMSource替换JAXBSource很容易:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM