DocumentBuilderFactory

DocumentBuilderFactory

我有以下代码:

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

我如何获取它来解析包含在字符串而不是文件中的XML?

最佳答案

我的代码库中有此功能,它应该对您有用。

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

另请参阅this similar question

10-06 10:32