使用JDOM将XML文件解析为尚未在XML文件中声明的外部DTD

时间:2011-01-24 15:09:43

标签: java xml dtd jdom dtd-parsing

在我的XML文件中,我有一些实体,例如’

所以我为我的XML文档创建了一个DTD标记来定义这些实体。下面是用于读取XML文件的Java代码。

SAXBuilder builder = new SAXBuilder();
URL url = new URL("http://127.0.0.1:8080/sample/subject.xml");        
InputStream stream = url.openStream();
org.jdom.Document document = builder.build(stream);

Element root = document.getRootElement();

Element name = root.getChild("name");
result = name.getText();
System.err.println(result);

如何更改Java代码以通过HTTP检索DTD以允许解析我的XML文档没有错误?

xml文档的简化示例。


<main>
  <name>hello &lsquo; world &rsquo; foo  &amp; bar </name> 
</main>

1 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是阅读文档,然后使用变换器对其进行验证:

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ValidateWithExternalDTD {
    private static final String URL = "http://127.0.0.1:8080/sample/subject.xml";
    private static final String DTD = "http://127.0.0.1/YourDTD.dtd";

    public static void main(String args[]) {
        try {
            DocumentBuilderFactory factory=                   DocumentBuilderFactory.newInstance();
            factory.setValidating(true);
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Set the error handler
            builder.setErrorHandler(new org.xml.sax.ErrorHandler() {                
                public void fatalError(SAXParseException spex)
                        throws SAXException {
                    // output error and exit
                    spex.printStackTrace();
                    System.exit(0);
                }

                public void error(SAXParseException spex)
                        throws SAXParseException {
                    // output error and continue
                    spex.printStackTrace();
                }

                public void warning(SAXParseException spex)
                        throws SAXParseException {
                    // output warning and continue
                    spex.printStackTrace();
                }
            });

            // Read the document
            URL url = new URL(ValidateWithExternalDTD.URL);
            Document xmlDocument = builder.parse(url.openStream());
            DOMSource source = new DOMSource(xmlDocument);

            // Use the tranformer to validate the document
            StreamResult result = new StreamResult(System.out);                     
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, ValidateWithExternalDTD.DTD);
            transformer.transform(source, result);

            // Process your document if everything is OK
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

另一种方法是用XML标题和DTD引用替换XML标题

替换它:

<?xml version = "1.0"?>

用这个:

<?xml version = "1.0"?><!DOCTYPE ...>

当然,您只会替换第一次出现,而不是尝试遍历整个xml文档

您必须通过将true(validate)传递给其构造函数来实例化SAXBuilder:

SAXBuilder builder = new SAXBuilder(true);

或致电:

builder.setValidation(true)