在Java中解析XML字符串的最佳方法? [英] Best way to parse an XML String in Java?

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

问题描述

我使用 javax.xml.parsers.DocumentBuilder 在Java中解析字符串。但是,没有直接解析String的函数,所以我这样做:

I am parsing a string in Java using javax.xml.parsers.DocumentBuilder. However, there is not a function to parse a String directly, so I am instead doing this:

public static Document parseText(String zText) {
    try
    {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(zText)));
        doc.getDocumentElement().normalize();
        return doc;
    }
    catch (Exception e) {
            e.printStackTrace();
    }
    return null;
}

这是最好的方法吗?我觉得必须有一个更简单的方法...谢谢!

Is this the best way to do it? I feel like there must be a simpler way... thanks!

推荐答案

直接回答你的问题 - 据我所知,那里不是更好的方式。使用输入源是因为它更通用,可以处理来自文件,字符串或线路的输入是我的理解。

To answer your question directly - to my knowledge, there is not a better way. The input source is used because it is more universal and can handle input from a file, a String or across the wire is my understanding.

您也可以尝试使用SAX Xml解析器 - 它更基本,并使用访问者模式,但它完成了工作,对于小型数据集和简单的XML模式,它非常容易使用。 SAX也包含在核心JRE中。

You could also try using the SAX Xml parser - it is a little more basic, and uses the Visitor Pattern, but it gets the job done and for smallish data sets and simple XML schemas it is pretty easy to use. SAX is also included with the core JRE.

这篇关于在Java中解析XML字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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