Answers:
我的代码库中有此功能,它应该对您有用。
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);
}
也看到这个类似的问题
import org.xml.sax.InputSource;
将字符串转换为InputStream并将其传递给DocumentBuilder
final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);
编辑
为了回应bendin关于编码的评论,请参阅shsteimer对这个问题的回答。
我正在使用这种方法
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;
}
javax.xml.parsers.DocumentBuilder.parse(string)
假设字符串是uri(糟糕……)