使用 JDOM 解析带有未在 XML 文件中声明的外部 DTD 的 XML 文件

发布于 2024-10-13 15:04:07 字数 694 浏览 2 评论 0原文

在我的 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>

In my XML file I have some entities such as

So I have created a DTD tag for my XML document to define these entities. Below is the Java code used to read the XML file.

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);

How can I change the Java code to retrieve a DTD over HTTP to allow the parsing of my XML document to be error free?

Simplified example of the xml document.


<main>
  <name>hello ‘ world ’ foo  & bar </name> 
</main>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舞袖。长 2024-10-20 15:04:07

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

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 标题替换为 XML 标题加上 DTD 引用

将其替换

<?xml version = "1.0"?>

为:

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

当然,您将替换第一次出现的情况仅而不是尝试遍历整个 xml 文档

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

SAXBuilder builder = new SAXBuilder(true);

或调用:

builder.setValidation(true)

One way to do this would be to read the document and then validate it with the transformer:

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();
        }
    }
}

Another way would be to replace the XML title with the XML title plus the DTD reference

Replace this:

<?xml version = "1.0"?>

with this:

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

Of course you would replace the first occurance only and not try to go through the whole xml document

You have to instantiate the SAXBuilder by passing true(validate) to its constructor:

SAXBuilder builder = new SAXBuilder(true);

or call:

builder.setValidation(true)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文