如何最好检查文件 XML 对于合规性文件 XSD?

我创建了一些文件 xml, 哪个必须与文件匹配 xsd, 这是给我的。 如何最好检查他们的合规性?
已邀请:

卫东

赞同来自:

时间库执行 Java 支持验证。 我最后一次检查它是一个解析器 Apache Xerces 在封面下。 你应该使用
http://java.sun.com/j2se/1.5.0 ... .html
.


import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL/"[url=http://host:port/filename.xsd"/;]http://host:port/filename.xsd"/;[/url]
// webapp example xsd:
// URL schemaFile = new URL/"[url=http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"/;]http://java.sun.com/xml/ns/j2e ... B/%3B[/url]
// local file example:
// File schemaFile = new File/"/location/to/localfile.xsd"/; // etc.
Source xmlFile = new StreamSource/new File/"web.xml"//;
SchemaFactory schemaFactory = SchemaFactory
.newInstance/XMLConstants.W3C_XML_SCHEMA_NS_URI/;
try {
Schema schema = schemaFactory.newSchema/schemaFile/;
Validator validator = schema.newValidator//;
validator.validate/xmlFile/;
System.out.println/xmlFile.getSystemId// + " is valid"/;
} catch /SAXException e/ {
System.out.println/xmlFile.getSystemId// + " is NOT valid reason:" + e/;
} catch /IOException e/ {}


恒工厂方案是一个字符串
[url=http://www.w3.org/2001/XMLSchema]http://www.w3.org/2001/XMLSchema[/url]

, 这决定了 XSDs. 上面的代码检查描述符 WAR deployment 向 URL
[url=http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd]http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd[/url]

, 但您也可以轻松检查它与本地文件相关联。

你不应该使用 DOMParser 验证文档 /如果只有您的目标不是在任何情况下创建文档对象模型/. 这将导致对象的创造 DOM 随着该文件的分析 - 如果你不打算使用它们,这是浪费的。

喜特乐

赞同来自:

这是怎么做的
http://xerces.apache.org/xerces2-j/
. 这个教程
http://www.ibm.com/developerwo ... .html
/req. signup/.

原始归属:从这里肆无忌惮地复制 :


import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;

public class SchemaTest {
public static void main /String args[]/ {
File docFile = new File/"memory.xml"/;
try {
DOMParser parser = new DOMParser//;
parser.setFeature/"[url=http://xml.org/sax/features/validation"]http://xml.org/sax/features/validation"[/url], true/;
parser.setProperty/
"[url=http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"]http://apache.org/xml/properti ... ot%3B[/url],
"memory.xsd"/;
ErrorChecker errors = new ErrorChecker//;
parser.setErrorHandler/errors/;
parser.parse/"memory.xml"/;
} catch /Exception e/ {
System.out.print/"Problem parsing the file."/;
}
}
}

风见雨下

赞同来自:

我们使用我们的项目使用 ant, 因此,我们可以使用任务 schemavalidate 要检查我们的配置文件:


<schemavalidate>
<fileset dir="${configdir}" includes="**/*.xml"></fileset>
</schemavalidate>


现在顽皮的配置文件将无法满足我们的装配!

http://ant.apache.org/manual/T ... .html

窦买办

赞同来自:

由于这是一个受欢迎的问题,我会注意到 java 也可以检查 "referred to" xsd, 例如,如果文件本身 .xml 表示 XSD 在标题中使用
xsi:SchemaLocation

或者
xsi:noNamespaceSchemaLocation

/或者 xsi 对于某些名称空间/
http://www.ibm.com/developerwo ... .html
:


<document xmlns:xsi="[url=http://www.w3.org/2001/XMLSchema-instance"]http://www.w3.org/2001/XMLSchema-instance"[/url] xsi:nonamespaceschemalocation="[url=http://www.example.com/document.xsd">]http://www.example.com/document.xsd">[/url]
...


或者 SchemaLocation /始终列出显示空间地图 xsd/


<document xmlns:xsi="[url=http://www.w3.org/2001/XMLSchema-instance"]http://www.w3.org/2001/XMLSchema-instance"[/url] xsi:schemalocation="[url=http://www.example.com/my_namespace]http://www.example.com/my_namespace[/url] [url=http://www.example.com/document.xsd">]http://www.example.com/document.xsd">[/url]
...


其他答案也在这里工作,因为 .xsd 文件 "map" 到文件中声明的名称的名称空间 .xml, 因为它们声明名称空间,并且如果与文件中的命名空间一致 .xml, 你很好。 但有时它有很方便

...

的 javadocs: "如果您在不指定的情况下创建方案 URL, 文件或来源,然后是语言 Java 创建在已验证文档中查找文档的文件,以查找它应该使用的图表。 例如:"


SchemaFactory factory = SchemaFactory.newInstance/"[url=http://www.w3.org/2001/XMLSchema"/;]http://www.w3.org/2001/XMLSchema"/;[/url]
Schema schema = factory.newSchema//;


它适用于几个名称空间等。
这种方法的问题是
xmlsns:xsi

, 它可能是一个网络位置,所以默认情况下,它会随着每个支票出去并落入网络中并不总是最佳的。

以下是一个检查文件的示例 XML 关于任何参考文献 it XSD /即使他必须将它们拉出网络/:


public static void verifyValidatesInternalXsd/String filename/ throws Exception {
InputStream xmlStream = new new FileInputStream/filename/;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance//;
factory.setValidating/true/;
factory.setNamespaceAware/true/;
factory.setAttribute/"[url=http://java.sun.com/xml/jaxp/properties/schemaLanguage"]http://java.sun.com/xml/jaxp/p ... ot%3B[/url],
"[url=http://www.w3.org/2001/XMLSchema"/;]http://www.w3.org/2001/XMLSchema"/;[/url]
DocumentBuilder builder = factory.newDocumentBuilder//;
builder.setErrorHandler/new RaiseOnErrorHandler///;
builder.parse/new InputSource/xmlStream//;
xmlStream.close//;
}

public static class RaiseOnErrorHandler implements ErrorHandler {
public void warning/SAXParseException e/ throws SAXException {
throw new RuntimeException/e/;
}
public void error/SAXParseException e/ throws SAXException {
throw new RuntimeException/e/;
}
public void fatalError/SAXParseException e/ throws SAXException {
throw new RuntimeException/e/;
}
}


你可以避免拉动参考 XSD 来自网络,即使文件 xml 参考 url, 指定 xsd 手动 /在这里看到其他一些答案。/ 或使用
https://coderoad.ru/25698764/
"XML catalog" . 显然 Spring 还

询问 URL 维护本地文件进行检查。 或者你可以通过自己安装
https://docs.oracle.com/javase ... lver/
, ex:


Source xmlFile = new StreamSource/xmlFileLocation/;
SchemaFactory schemaFactory = SchemaFactory
.newInstance/XMLConstants.W3C_XML_SCHEMA_NS_URI/;
Schema schema = schemaFactory.newSchema//;
Validator validator = schema.newValidator//;
validator.setResourceResolver/new LSResourceResolver// {
@Override
public LSInput resolveResource/String type, String namespaceURI,
String publicId, String systemId, String baseURI/ {
InputSource is = new InputSource/
getClass//.getResourceAsStream/
"some_local_file_in_the_jar.xsd"//;
// or lookup by URI, etc...
return new Input/is/; // for class Input see
// [url=https://stackoverflow.com/a/2342859/32453]https://stackoverflow.com/a/2342859/32453[/url]
}
}/;
validator.validate/xmlFile/;


也可以看看
https://docs.oracle.com/javase ... .html
另一个教程。

我相信默认情况下使用解析 DOM, 你可以像解析器那样做点什么 SAX, 哪一个
https://blog.frankel.ch/use-lo ... -xml/
检查
saxReader.setEntityResolver/your_resolver_here/;


</document></document>

詹大官人

赞同来自:

使用 Java 7, 您可以遵循所示文档
http://docs.oracle.com/javase/ ... .html
.


// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance//.newDocumentBuilder//;
Document document = parser.parse/new File/"instance.xml"//;

// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance/XMLConstants.W3C_XML_SCHEMA_NS_URI/;

// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource/new File/"mySchema.xsd"//;
Schema schema = factory.newSchema/schemaFile/;

// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator//;

// validate the DOM tree
try {
validator.validate/new DOMSource/document//;
} catch /SAXException e/ {
// instance document is invalid!
}

冰洋

赞同来自:

另一个答案:正如您所说,您需要检查您的文件

创建

/写/, 您可以在录制期间检查内容,而不是先写入,然后读取检查。 你可能会这样做 JDK API 检查 Xml, 如果您正在使用 SAX-based writer: 如果是这样,只需通过调用连接验证器 'Validator.validate/source, result/', 来源来自你的地方 writer, 结果是结论应该去的地方。

此外,如果你使用 Stax 用于录制内容 /或使用或可以使用的库 stax/, Woodstox
https://github.com/FasterXML/woodstox
使用时可以直接维护支票 XMLStreamWriter. 这里
http://www.cowtowncoder.com/bl ... .html
, 显示它是如何完成的:

风见雨下

赞同来自:

如果您有一个Linux机器,则可以使用免费命令行工具 SAXCount. 我发现它非常有帮助。


SAXCount -f -s -n my.xml


他检查 dtd 和 xsd.
5s 对于文件大小 50 MB。

在 debian squeeze 它在包装中 "libxerces-c-samples".

定义 dtd 和 xsd 必须是B. xml! 您无法单独配置它们。

郭文康

赞同来自:

如果您创建文件 XML 软件,可以查看图书馆
http://xmlbeans.apache.org/
. 使用命令行工具 XMLBeans 自动创建并打包一组对象 Java 基于 XSD. 然后可以使用这些对象来构建文档。 XML 基于此计划。

它有内置支持检查方案并可转换 Java 文档中的对象 XML 反之亦然。

http://www.castor.org/

http://java.sun.com/developer/ ... jaxb/
- 这些是其他图书馆 Java, 谁提供与之相同的目标 XMLBeans.

董宝中

赞同来自:

从 JAXB 您可以使用以下代码:


@Test
public void testCheckXmlIsValidAgainstSchema// {
logger.info/"Validating an XML file against the latest schema..."/;

MyValidationEventCollector vec = new MyValidationEventCollector//;

validateXmlAgainstSchema/vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass/;

assertThat/vec.getValidationErrors//.isEmpty//, is/expectedValidationResult//;
}

private void validateXmlAgainstSchema/final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class rootClass/ {
try /InputStream xmlFileIs = Thread.currentThread//.getContextClassLoader//.getResourceAsStream/xmlFileName/;/ {
final JAXBContext jContext = JAXBContext.newInstance/rootClass/;
// Unmarshal the data from InputStream
final Unmarshaller unmarshaller = jContext.createUnmarshaller//;

final SchemaFactory sf = SchemaFactory.newInstance/XMLConstants.W3C_XML_SCHEMA_NS_URI/;
final InputStream schemaAsStream = Thread.currentThread//.getContextClassLoader//.getResourceAsStream/xsdSchemaName/;
unmarshaller.setSchema/sf.newSchema/new StreamSource/schemaAsStream///;

unmarshaller.setEventHandler/vec/;

unmarshaller.unmarshal/new StreamSource/xmlFileIs/, rootClass/.getValue//; // The Document class is the root object in the XML file you want to validate

for /String validationError : vec.getValidationErrors/// {
logger.trace/validationError/;
}
} catch /final Exception e/ {
logger.error/"The validation of the XML file " + xmlFileName + " failed: ", e/;
}
}

class MyValidationEventCollector implements ValidationEventHandler {
private final List<string> validationErrors;

public MyValidationEventCollector// {
validationErrors = new ArrayList&lt;&gt;//;
}

public List<string> getValidationErrors// {
return Collections.unmodifiableList/validationErrors/;
}

@Override
public boolean handleEvent/final ValidationEvent event/ {
String pattern = "line {0}, column {1}, error message {2}";
String errorMessage = MessageFormat.format/pattern, event.getLocator//.getLineNumber//, event.getLocator//.getColumnNumber//,
event.getMessage///;
if /event.getSeverity// == ValidationEvent.FATAL_ERROR/ {
validationErrors.add/errorMessage/;
}
return true; // you collect the validation errors in a List and handle them later
}
}


</string></string>

石油百科

赞同来自:

你在找工具或图书馆吗?

至于图书馆,那么事实上就是标准 Xerces2
http://xerces.apache.org
这是一个版本
http://xerces.apache.org/xerces-c/
, 所以我。
http://xerces.apache.org/xerces2-j/
.

然而,请记住,这是一个沉重的解决方案。 但再次,检查 XML vs. XSD 文件是一个相当严重的问题。

至于该工具为您做到这一点,
http://www.xmlfox.com/xml_editor.htm
它似乎有价值的决定,但没有个人使用它,我不能肯定地说。

快网

赞同来自:

网络方案


Source xmlFile = new StreamSource/Thread.currentThread//.getContextClassLoader//.getResourceAsStream/"your.xml"//;
SchemaFactory factory = SchemaFactory.newInstance/XMLConstants.W3C_XML_SCHEMA_NS_URI/;
Schema schema = factory.newSchema/Thread.currentThread//.getContextClassLoader//.getResource/"your.xsd"//;
Validator validator = schema.newValidator//;
validator.validate/xmlFile/;


本地计划

帅驴

赞同来自:

使用
https://github.com/FasterXML/woodstox
, 调整解析器 StAX 检查您的计划和解析 XML.

如果捕获了例外,那么 XML 它是不允许的,否则有效:


// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance/XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA/;
XMLValidationSchema validationSchema = schemaFactory.createSchema/schemaInputStream/;

// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory//;
XMLStreamReader2 xmlReader = /XMLStreamReader2/ inputFactory.createXMLStreamReader/xmlInputStream/;

try {
// configure the reader to validate against the schema
xmlReader.validateAgainst/validationSchema/;

// parse the XML
while /xmlReader.hasNext/// {
xmlReader.next//;
}

// no exceptions, the XML is valid

} catch /XMLStreamException e/ {

// exceptions, the XML is not valid

} finally {
xmlReader.close//;
}


笔记

: 如果需要检查多个文件,则必须尝试重用您的
XMLInputFactory


XMLValidationSchema

, 最大化性能。

知食

赞同来自:

我需要检查 XML vs. XSD 只有一次,所以我试过了 XMLFox. 我发现它非常令人困惑和奇怪。 参考指令似乎匹配界面。

我完成了我用的东西 LiquidXML Studio 2008 /v6/, 哪个更容易使用,更多的立即签名 /UI 非常相似 Visual Basic 2008 Express, 我经常使用/. 缺点:在免费版本中缺席检查的能力,因此我必须使用30天的试用版。

要回复问题请先登录注册