Home > Java > javaTutorial > body text

How to Extract Element Values from XML in Java?

Susan Sarandon
Release: 2024-11-07 04:19:03
Original
216 people have browsed it

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)));
Copy after login

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");
Copy after login

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();
    }
}
Copy after login

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>
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!