如何使用 Java 检索 XML 的元素值? [英] How to retrieve element value of XML using Java?

查看:33
本文介绍了如何使用 Java 检索 XML 的元素值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XML 的新手.我想根据请求名称阅读以下 XML.请帮助我如何在 Java 中阅读以下 XML -

I am new to XML. I want to read the following XML on the basis of request name. Please help me on how to read the below XML in Java -

<?xml version="1.0"?>
    <config>
        <Request name="ValidateEmailRequest">
            <requestqueue>emailrequest</requestqueue>
            <responsequeue>emailresponse</responsequeue>
        </Request>
        <Request name="CleanEmail">
            <requestqueue>Cleanrequest</requestqueue>
            <responsequeue>Cleanresponse</responsequeue>
        </Request>
    </config>

推荐答案

如果你的 XML 是一个字符串,那么你可以这样做:

If your XML is a String, Then you can do the following:

String xml = ""; //Populated XML String....

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();

如果您的 XML 在文件中,那么 Document 文档 将像这样实例化:

If your XML is in a file, then Document document will be instantiated like this:

Document document = builder.parse(new File("file.xml"));

document.getDocumentElement() 返回作为文档的文档元素的节点(在您的情况下为 ).

The document.getDocumentElement() returns you the node that is the document element of the document (in your case <config>).

一旦你有了rootElement,你就可以访问元素的属性(通过调用rootElement.getAttribute()方法)等等.更多关于java的org.w3c.dom.Element

Once you have a rootElement, you can access the element's attribute (by calling rootElement.getAttribute() method), etc. For more methods on java's org.w3c.dom.Element

有关 Java 的更多信息 DocumentBuilder &DocumentBuilderFactory.请记住,提供的示例创建了一个 XML DOM 树,因此如果您有大量的 XML 数据,该树可能会很大.

More info on java DocumentBuilder & DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.

更新 这是一个获取元素

protected String getString(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        if (list != null && list.getLength() > 0) {
            NodeList subList = list.item(0).getChildNodes();

            if (subList != null && subList.getLength() > 0) {
                return subList.item(0).getNodeValue();
            }
        }

        return null;
    }

你可以有效地称之为,

String requestQueueName = getString("requestqueue", element);

这篇关于如何使用 Java 检索 XML 的元素值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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