在 Java 中,如何将 XML 解析为字符串而不是文件? [英] In Java, how do I parse XML as a String instead of a file?

查看:31
本文介绍了在 Java 中,如何将 XML 解析为字符串而不是文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

How can I get it to parse XML contained within a String instead of a file?

推荐答案

我的代码库中有这个功能,这应该适合你.

I have this function in my code base, this should work for you.

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

另见这个类似的问题

这篇关于在 Java 中,如何将 XML 解析为字符串而不是文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆