如何使用Java检索XML的元素值

如何使用Java检索XML的元素值

本文介绍了如何使用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是String,那么你可以做以下内容:

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在一个文件中,那么文档文件将实例化如下:

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()返回给你作为文档文档元素的节点(在您的情况下为< config> )。

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

一旦你有 rootElement ,你可以访问元素的属性(通过调用 rootElement.getAttribute()方法)等等。关于java的

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的更多信息& 。 请记住,提供的示例创建了一个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.



  • Related question.

更新以下是获取元素$的元素< requestqueue>

Update Here's an example to get "value" of element <requestqueue>

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

您可以有效地将其称为,

You can effectively call it as,

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

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

08-21 09:05