user906153
user906153

Reputation: 1218

Accessing values using XML keyname

I have XML similar to this contained in a Document object (org.w3c.dom.Document) in my code:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <key keyname="info"> </key>
    <key keyname="name"/>
    <key keyname="address"/>
    <key keyname="id">13</key>
</root>

I would like to be able to access each key node and print out its value, and be able to print out each value with its corresponding keyname

I have never worked with XML using keyname before, how do I access these values?

Upvotes: 0

Views: 50

Answers (1)

Braj
Braj

Reputation: 46871

It's very simple using DOM parser using getAttributes().getNamedItem("keyname") method.

sample code:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class SpringXMLParser {

    public static void parse(String file) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(new FileInputStream(file));
        Element root = doc.getDocumentElement();
        org.w3c.dom.NodeList nodeList = root.getElementsByTagName("key");
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.print(((Node) nodeList.item(i))
                     .getAttributes().getNamedItem("keyname"));
            System.out.println("\tvalue: "+((Node) nodeList.item(i)).getTextContent());
        }

    }

    public static void main(String args[]) throws Exception {
        parse("resources/xml5.xml");
    }
}

output:

keyname="info"      value:  
keyname="name"      value: 
keyname="address"   value: 
keyname="id"        value: 13

Upvotes: 1

Related Questions