Home >Java >javaTutorial >How to Extract Element Values from XML in Java?

How to Extract Element Values from XML in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 04:19:03283browse

How to Extract Element Values from XML in Java?

Java XML Element Value Extraction

XML parsing is a crucial task in various programming scenarios. Let's explore how to retrieve element values from XML in Java.

Accessing XML using Java

To work with XML in Java, you need to instantiate a DocumentBuilder object using DocumentBuilderFactory. Once you have a DocumentBuilder, you can parse the XML into a Document object using DocumentBuilder.parse().

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

Retrieving Element Values

To retrieve the value of an element, use the getElementsByTagName() method on the Document object. This method returns a NodeList containing all elements with the specified tag name.

NodeList list = document.getElementsByTagName("requestqueue");

Element Value Extraction

Once you have the NodeList, you can access the value of the first element using the getNodeValue() method.

if (list != null && list.getLength() > 0) {
    NodeList subList = list.item(0).getChildNodes();
    if (subList != null && subList.getLength() > 0) {
        String value = subList.item(0).getNodeValue();
    }
}

Example

Consider the following XML:

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

To retrieve the value of the element for the "ValidateEmailRequest" request:

 Element rootElement = document.getDocumentElement();
 Element request = (Element) rootElement.getElementsByTagName("Request").item(0);
 String requestQueueName = getString("requestqueue", request);

The above is the detailed content of How to Extract Element Values from XML in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn