In Java, how do I parse XML as a String instead of

2019-01-01 10:04发布

I have the following code:

DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

How can I get it to parse XML contained within a String instead of a file?

6条回答
查无此人
2楼-- · 2019-01-01 10:40

One way is to use the version of parse that takes an InputSource rather than a file

A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader

So something like

parse(new InputSource(new StringReader(myString))) may work. 
查看更多
只若初见
3楼-- · 2019-01-01 10:43

Convert the string to an InputStream and pass it to DocumentBuilder

final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);

EDIT
In response to bendin's comment regarding encoding, see shsteimer's answer to this question.

查看更多
谁念西风独自凉
4楼-- · 2019-01-01 10:46

I have this function in my code base, this should work for you.

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

also see this similar question

查看更多
十年一品温如言
5楼-- · 2019-01-01 10:47

You can use the Scilca XML Progession package available at GitHub.

XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();
查看更多
皆成旧梦
6楼-- · 2019-01-01 10:48

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}
查看更多
只若初见
7楼-- · 2019-01-01 10:52

javadocs show that the parse method is overloaded.

Create a StringStream or InputSource using your string XML and you should be set.

查看更多
登录 后发表回答