1

I've been at this for days and cannot find a way to parse this XML file. I've tried XMLPullParser, SAX and now DOM, but as soon as I'd made some progress, I realized that I have two different <con> tags. I'm new to Java and Android, and especially new to XML parsing, so any help would mean a lot.

Here's a segment of the xml file:

<data>
      <con id="f3cVQQjz8jr">
        <con idref="nJ4haotQTo0"/>
        <added order="9">2013-08-22T03:14:13.439Z</added>
        <name>Alex</name>
        <rank>0</rank>
      </con>
      <con id="nJ4haotQTo0">
        <added order="10">2013-08-22T03:14:13.439Z</added>
        <name>Charley</name>
        <rank>-2</rank>
      </con>
      <con id="jadh7bH25mI">
        <added order="11">2013-08-22T03:14:13.439Z</added>
        <name>David</name>
        <rank>1227133510</rank>
      </con>
      <con id="erfhZ_dn0HA">
        <con idref="nJ4haotQTo0"/>
        <added order="12">2013-08-22T03:14:13.439Z</added>
        <name>Sebastien</name>
        <rank>1073741824</rank>
      </con>
</data>

As you can see, not all sections have a child <con> tag, so I don't think using a counter would work.

Here's my latest attempt (doesn't do anything about the nested <con> tags):

 public void parseContext()
    {
        NodeList nodeList = doc.getElementsByTagName("con");
        int size = nodeList.getLength();
        for(int i = 0 ; i < size ; i++)
        {


            System.out.println("---------------Context ("+i+")--------------------");
            Node node = nodeList.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE)
            {
                Element e = (Element) node;
                NodeList resultNodeList = e.getElementsByTagName("name");
                int resultNodeListSize = resultNodeList.getLength();
                for(int j = 0 ; j < resultNodeListSize ; j++ )
                {
                    Node resultNode = resultNodeList.item(j);
                    if(resultNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element resultE = (Element) resultNode;
                        System.out.println("Context Name :"+resultE.getTextContent());
                    }
                }
            }
        }

    }

Which results in:

---------------Context (0)--------------------
Context Name :Alex
---------------Context (1)--------------------
Context Name :Charley
---------------Context (2)--------------------
---------------Context (3)--------------------
Context Name :David
---------------Context (4)--------------------
Context Name :Sebastien
---------------Context (5)--------------------
...

What I'd like to have is something like this:

---------------Context (0)--------------------
Context Name :Alex
Context ID Ref: duRjfksjf0
---------------Context (1)--------------------
Context Name :Charley
Context ID Ref: null
---------------Context (3)--------------------
Context Name :David
Context ID Ref: null
---------------Context (4)--------------------
Context Name :Sebastien
Context ID Ref: iJ4hasftQTo0
---------------Context (5)--------------------
....

Again, the document is much longer, and there is no pattern between whether or not there is an idref. I will eventually be parsing all the data within the parent <con> tags, but I would be able to figure that out if I knew how to deal with the child <con> tag.

I searched and found this: How to differentiate parent and child tag while dom parsing? though there were no helpful answers. No questions I found involved tags with same names on different levels. I know there're a lot of similar questions, and will understand if this gets deleted. Though again, I'd really appreciate the help.

1
  • Post the link for that xml... Commented Aug 23, 2013 at 5:13

3 Answers 3

0

Try this ...

if(node.getNodeType() == Node.ELEMENT_NODE){
    Element e = (Element) node;
    NodeList resultNodeList = e.getElementsByTagName("con");           

    if(!e.hasAttribute("idref")){
        if(resultNodeList.getLength() == 2){
            Element nameElement = (Element) resultNodeList.item(1); 
            if(!nameElement.hasAttribute("idref"))
                 System.out.println("Context ID Ref : "+null);
            else    
                 System.out.println("Context ID Ref :"+nameElement.getAttribute("idref"));
        }else {
            Element nameElement = (Element) resultNodeList.item(0);   
            if(!nameElement.hasAttribute("idref"))
                 System.out.println("Context ID Ref : "+null);
            else    
                 System.out.println("Context ID Ref :"+nameElement.getAttribute("idref"));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
  Node node = nodeList.item(i);     
    NodeList list = node.getChildNodes(); 
    for (int i = 0; i < list.getLength(); i++) {

               Node childnode = list.item(i);

       if ("con".equals(childnode.getNodeName())) {
        //it have a second con tag
       }
             }

take a look of this: http://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/

Comments

0

This is similar to what I have just done for my project. I prefer to write some common methods in order to reuse it in other places.

package com.practice;

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class XMLHelper {

public static void main(String[] args) {
    parseContext();
}

public static Document createDocumentFromFile() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document = null;

    try {
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();

        document = db.parse("xmltest.txt");

    } catch (Exception e) {
        e.printStackTrace();
    }

    return document;
}

public static Element converDocumentToElement(Document document) {
    Element rootElement = null;

    if (document != null) {
        document.getDocumentElement().normalize();
        rootElement = document.getDocumentElement();
    }

    return rootElement;
}


public static List<Element> getElementsByName(Element elem, String name) {
    List<Element> elements = null;

    if (elem == null) return elements;

    NodeList nodeList = elem.getElementsByTagName(name);

    if (nodeList == null || nodeList.getLength() == 0) return elements;

    elements = new ArrayList<Element>();

    for (int i=0; i<nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        elements.add(element);
    }

    return elements;
}


public static void parseContext() {
    Document document = createDocumentFromFile();
    Element rootElement = converDocumentToElement(document);

    List<Element> outsideConElements = getElementsByName(rootElement, "con");

    if (outsideConElements == null) {
        System.out.println("no <con> is found!");
    } else {
        for (Element outsideConElement : outsideConElements) {
            List<Element> insideConElements = getElementsByName(outsideConElement, "con");

            if (insideConElements != null && !insideConElements.isEmpty()) {
                Element insideConElement = insideConElements.get(0);
                if (insideConElement != null)
                    System.out.println(insideConElement.getAttribute("idref"));
            }
        }
    }

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.