mosawi
mosawi

Reputation: 1323

How to get Key value pair from XML document Java

I have an XML document from which I would like to retrieve the key and value from this XML document. However I am have trouble getting both, I realize I should use the data type of Map but I am unsure how to accomplish this.

Example:

I have the following XML file:

<?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>

I'd like to write a method which parses this file and returns me a key value pair of the node (key) and value (value) of the XML.

Such as [requestqueue,emailrequest] [responsequeue,emailresponse], etc...

What I currently have:

public Map<String, String> parseXML(File f) throws Exception {

    String xml = FileUtils.readFileToString(f);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(new InputSource(new StringReader(xml)));
    Element rootElement = document.getDocumentElement();

    // I'm stuck...

    return null;
}

Any help or assistance would be much appreciated, thanks.

Edit:

I did some research and I found something that will print me the values but only 1 of the keys "Return"

@Test
public void testConverter() throws Exception {
    String xml = ("xmlDir/request.xml");
    Map<String,String> map = convertNodesFromXml(xml);

    for(Map.Entry<String, String> entry: map.entrySet()) {
        String key = entry.getKey(); 
        String value = entry.getValue();

        logger.debug("Key: "+key+" Value: "+value);
    }

}



public static Map<String, String> convertNodesFromXml(String xml) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(xml);

    Element doc = document.getDocumentElement();
    logger.debug(doc.getFirstChild());

    return createMap(document.getDocumentElement());
}

public static Map<String, String> createMap(Node node) {
    Map<String, String> map = new HashMap<String, String>();
    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.hasAttributes()) {
            for (int j = 0; j < currentNode.getAttributes().getLength(); j++) {
                Node item = currentNode.getAttributes().item(i);
                map.put(item.getNodeName(), item.getTextContent());
            }
        }
        if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
            map.putAll(createMap(currentNode));
        } else if (node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
            map.put(node.getLocalName(), node.getTextContent());
        }
    }
    return map;
}

Output:

2015-08-18 15:01:31,651 : Key: Return Value: 



    136
    125
    SEPTEMBER
    250


    OCTOBER
    250
    125
    136


    136
    125
    250
    APRIL


    136
    JUNE
    250
    125


    MAY
    136
    250
    125


    136
    250
    125
    JANUARY


    136
    125
    250
    MARCH


    250
    AUGUST
    136
    125

  3000

    136
    125
    250
    DECEMBER


    136
    JULY
    125
    250


    136
    125
    FEBRUARY
    250

  1500
  555-11-2222

    125
    136
    NOVEMBER
    250

  1632


  1
  22000
  1
  22000




  1970-01-01


  555-11-2222


      CA

Upvotes: 2

Views: 9199

Answers (2)

stuparm
stuparm

Reputation: 553

Have you look at java documentation

First of all I will try with

NodeList nodeList = rootElement.getElementsByTagName("equestqueue");

And later I will iterate through this List (also look at the api) and find attributes, values etc...

Upvotes: 0

pernpas
pernpas

Reputation: 199

The function getChildNodes() https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getChildNodes() returns a nodelist which contains the children of this node. Maybe you make use of that function to walk through your nodetree. Alternatively you can use a frameworks like Jaxb which maps your xml into Java Pojos. With that pojos you can build your map

Upvotes: 0

Related Questions