字符串作为文档

发布于 2024-10-04 02:53:32 字数 407 浏览 3 评论 0原文

我正在遵循有关使用 XPath 解析 XML 的教程,它给出了打开文档的以下示例:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");

我想做的是更改它,以便 Document 正在读取 我已经创建的 String 变量,而不是从文件中读取。我怎样才能做到这一点?

I'm following this turorial on parsing XML with XPath, and it gives the following example to open a document:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");

What I would like to do, is change that so that the Document is reading a String variable that I already have made, instead of reading from a file. How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

落在眉间の轻吻 2024-10-11 02:53:32
builder.parse(new InputSource(new StringReader("<some><xml></xml></some>")));
builder.parse(new InputSource(new StringReader("<some><xml></xml></some>")));
笑着哭最痛 2024-10-11 02:53:32

请查看此处

DocumentBuilderFactory dbf =
        DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);

Look here

DocumentBuilderFactory dbf =
        DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
转角预定愛 2024-10-11 02:53:32

你可以试试这个:

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

You may try this one:

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)));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文