我在String变量中有一个XML,我想将该值传递到DocumentBuilder的parse()中。

String xml = "<?xml version="1.0 ....>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));


但是,似乎最后一行不起作用,因为doc为null。

这有什么问题吗?我只是尝试将xml值并将其转换为Document。

感谢帮助。

最佳答案

您需要更近的东西

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));


您可以将其修剪为:

DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));


请注意,通常您会期望一个XML文件,并且它是:

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fullpathtofile));

09-08 07:37