我如何加载一个org.w3c.dom。XML文档中的字符串?

时间:2022-10-30 13:44:18

I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)

我在一个字符串中有一个完整的XML文档,它就像一个文档对象。谷歌出现了各种各样的垃圾。最简单的解是什么?(在Java 1.5)

Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.)

感谢Matt McMinn,我已经解决了这个问题。它为我提供了合适的输入灵活性和异常粒度。(很高兴知道这个错误来自于malformed的XML - SAXException,或者只是糟糕的IO - IOException。)

public static org.w3c.dom.Document loadXMLFrom(String xml)
    throws org.xml.sax.SAXException, java.io.IOException {
    return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));
}

public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) 
    throws org.xml.sax.SAXException, java.io.IOException {
    javax.xml.parsers.DocumentBuilderFactory factory =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    javax.xml.parsers.DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    }
    catch (javax.xml.parsers.ParserConfigurationException ex) {
    }  
    org.w3c.dom.Document doc = builder.parse(is);
    is.close();
    return doc;
}

4 个解决方案

#1


71  

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

这在Java 1.5中对我有效——我删除了可读性的特定异常。

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

#2


135  

Whoa there!

哇!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

这段代码有一个潜在的严重问题,因为它忽略了字符串中指定的字符编码(默认情况下是UTF-8)。当您调用String.getBytes()时,使用平台默认编码将Unicode字符编码为字节。因此,解析器可能会认为它得到了UTF-8数据,实际上,它得到了EBCDIC或其他什么,不漂亮!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

相反,使用使用InputSource的解析方法,该方法可以由一个读取器构建,如下所示:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

这似乎不是什么大问题,但对字符编码问题的无知导致了类似于y2k的潜在代码腐烂。

#3


9  

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

只是有一个类似的问题,除了我需要一个NodeList而不是一个文档,这是我提出的。它与之前的解决方案基本相同,增强了将根元素作为NodeList,并使用erickson的建议使用InputSource代替字符编码问题。

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

#4


1  

To manipulate XML in Java, I always tend to use the Transformer API:

为了在Java中操作XML,我总是倾向于使用Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

#1


71  

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

这在Java 1.5中对我有效——我删除了可读性的特定异常。

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

#2


135  

Whoa there!

哇!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

这段代码有一个潜在的严重问题,因为它忽略了字符串中指定的字符编码(默认情况下是UTF-8)。当您调用String.getBytes()时,使用平台默认编码将Unicode字符编码为字节。因此,解析器可能会认为它得到了UTF-8数据,实际上,它得到了EBCDIC或其他什么,不漂亮!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

相反,使用使用InputSource的解析方法,该方法可以由一个读取器构建,如下所示:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

这似乎不是什么大问题,但对字符编码问题的无知导致了类似于y2k的潜在代码腐烂。

#3


9  

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

只是有一个类似的问题,除了我需要一个NodeList而不是一个文档,这是我提出的。它与之前的解决方案基本相同,增强了将根元素作为NodeList,并使用erickson的建议使用InputSource代替字符编码问题。

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

#4


1  

To manipulate XML in Java, I always tend to use the Transformer API:

为了在Java中操作XML,我总是倾向于使用Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}