简体   繁体   English

根据DTD编写XML

[英]Writing XML according to a DTD

I would like to know if there is a way (particularly, an API ), in Java, to write a XML in a SAX-like way (ie, event-like way, differently from JDOM, which I cannot use) that takes a DTD and guarantees that my XML document is being correctly written. 我想知道在Java中是否有一种方法(特别是API )以类似于SAX的方式(即,类似于Event的方式,不同于我不能使用的JDOM)编写XML,而该方式需要DTD,并保证正确编写了我的XML文档。

I have been using SAX for parsing and I have written a XML writer layer by myself as if I were writing a plain file (through OutputStreamWriter ), but I have seen that my XML writer layer is not always following the DTD rules. 我一直在使用SAX进行解析,并且我自己编写了XML编写器 ,就好像我在编写纯文件一样(通过OutputStreamWriter ),但是我发现我的XML编写器并不总是遵循DTD规则。

SAX does not know to write XML documents. SAX不知道编写XML文档。 It is attended to parse them. 有人来解析它们。 So, you can choose any method you want to create document and then validate it using SAX API against DTD. 因此,您可以选择要创建文档的任何方法,然后针对DTD使用SAX API对其进行验证。

BTW may I ask you why are you limiting yourself to using tools that were almost obsolete about 10 years ago? 顺便说一句,我想问你,为什么要限制自己使用大约十年前已经过时的工具? Why not to use higher level API that converts objects to XML and vice versa? 为什么不使用将对象转换为XML,反之亦然的高级API? For example JAXB. 例如JAXB。

The Standard DocumentBuilder methodology can validate for you. 标准DocumentBuilder方法可以为您验证。

This snippet taken from http://www.edankert.com/validate.html#Validate_using_internal_DTD 该摘录摘自http://www.edankert.com/validate.html#Validate_using_internal_DTD

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);

SchemaFactory schemaFactory = 
    SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

factory.setSchema(schemaFactory.newSchema(
    new Source[] {new StreamSource("contacts.xsd")}));

DocumentBuilder builder = factory.newDocumentBuilder();

builder.setErrorHandler(new SimpleErrorHandler());

Document document = builder.parse(new InputSource("document.xml"));

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

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