我正在关注使用XPath解析XML的这个问题,它给出了以下示例来打开文档:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
我想做的是改变它,以便Document
正在读取我已经创建的String
变量,而不是从文件中读取。我怎么能这样做?
答案 0 :(得分:5)
builder.parse(new InputSource(new StringReader("<some><xml></xml></some>")));
答案 1 :(得分:2)
看here
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
答案 2 :(得分:0)
你可以尝试这个:
public static Document stringToDom(String xmlSource)
throws SAXException, ParserConfigurationException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(xmlSource)));
}