1

I am not sure how accurately ask my questions. I believe two questions may help:

I have been playing with parsing files – xml in particular.

I have found many tutorials and many flavors of techniques.

Most of the tutorials have a simple xml file to start with containing names, phone numbers and so forth.

My 2 questions:

1) how can I extract / display just the data between a specific . For example if I just want to display the <FirstNames> how can I do (in Java) the following:

loop

If <tag> = “FirstName” then name_variable = data in between tags);

or

If <tag> = “FirstName” then System.out.printf(“ the first name is %s\n”,name_variable);

end loop

2) Suppose I am looking for only the second instance of the First Name, in some tutorials/examples I have seen how to display all the data from within a loop. I have attempted to set the data equal to an “arrayed” string and then display the data outside the loop but have struck out. Bottom line, how do you store an indexed (array) piece of parsed XML data for use or passing in later code?

<company>
<Name>My Company</Name>
<Executive type = "CEO">
    <LastName>Smith</LastName>
    <FirstName>Jim</FirstName>
    <street>123 Main Street</street>
    <city>Mytown</city>
    <state>TN</state>
    <zip>11234</zip>
</Executive>
<Executive type = "OEC">
    <LastName>Jones</LastName>
    <FirstName>John</FirstName>
    <street>456 Main Street</street>
    <city>Gotham</city>
    <state>TN</state>
    <zip>11234</zip>
</Executive>
</company>

Here is some code I have pieced together, I am getting some data from my XML but I have not figured out how to store in a indexed piece of parsed data.

package dom_parsing_in_java;
import  org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
//import com.sun.org.apache.xerces.internal.parsers.DOMParser;

public class DOM_Parsing_In_JAVA {

   public static void main(String[] args) {
    // TODO code application logic here
    String file = "test2.xml";

if(args.length >0){
    file = args[0];

}// end If

try{
    //DOMParser parser= new DOMParser();
    DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new File(file));

    //Document document = parser.getDocument();

    Element root = document.getDocumentElement();
    System.out.println(root.getTagName());

    NodeList node_list = root.getElementsByTagName("Executive");


   //Node comp = getNode("Company",root);

    int i;


    for(i = 0; i<node_list.getLength();i++){
        Element department = (Element)node_list.item(i);

        System.out.println(department.getTagName());
        System.out.println("name "+document.getElementsByTagName("Name").item(0).getTextContent());
        System.out.println("name "+document.getElementsByTagName("FirstName").item(i).getTextContent());
        System.out.printf(" Lastname: %s%n ", document.getElementsByTagName("LastName").item(i));
        System.out.printf(" Lastname: %s%n ", department.getAttribute("LastName"));
        System.out.printf(" FirstName: %s%n",department.getAttribute("FirstName"));
        //System.out.printf(" elements by Tag %s%n",department.getElementsByTagName("testTag"));
        //System.out.printf(" staff: %s%n",countStaff(department));
    }

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

}//end catch
}
}

2 Answers 2

0

Have a look at the StAX API: http://docs.oracle.com/javase/tutorial/jaxp/stax/why.html

(You probably want to use its "iterator/ event API": http://docs.oracle.com/javase/tutorial/jaxp/stax/api.html )

Here is a sample: http://docs.oracle.com/javase/tutorial/jaxp/stax/example.html#bnbfz

2
  • I spent last night (too late last night) getting frustrated with attempting to work through the StAX examples and reading a little. A decent level of frustration sat in last night. I have been steadily searching the web for instructions on parsing an XML in JAVA. My end goal I think is rather simple – extract and store in a variable a specific piece of “tagged” XML data and use it elsewhere. Last week I got real close using DOM but couldn’t get the data stored and passed to another part. I could display it and felt like I was almost there. I could use some additional advice and direction.
    – user638361
    Feb 27, 2013 at 14:14
  • I read and worked through the links mentioned. I feel like the examples mentioned in docs.oracle.com/javase/tutorial/jaxp/stax/example.html#bnbfz Assume a certain level of JAVA proficiency – it appears that the examples were giving snip-its and partial pieces of code and the remaining code should be obvious. I could use some additional advice and direction. Thanks!
    – user638361
    Feb 27, 2013 at 14:15
0

I'd go down the XPath-route and parse the XML file into a Document.

XPaths can be used to navigate an XML document. See http://www.w3schools.com/xpath/default.asp for more information on what you can achieve with XPaths.

Assuming everything is done in main:

public static void main(String[] args) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("file.xml"));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression firstnameExpr = xpath.compile("//FirstName");

    NodeList nl = (NodeList) firstnameExpr.evaluate(doc, XPathConstants.NODESET);

    for (int i=0; i<nl.getLength(); i++) {
        Node node = nl.item(i);

        // this is assuming the first child of Firstname is the characters (contents)
        // of the Firstname tag, you may need to do some checking whether or not
        // node.getNodeType() == Node.Text;
        System.out.println("Firstname["+i+"] = " 
                                + node.getChildNodes()[0].getTextContent());
    }


}

Instead of printing the first name contents to System.out you could add the values to a ArrayList which would maintain the order, i.e:

List<String> firstnameList = new ArrayList<String>();

for (int i=0; i<nl.getLength(); i++) {
    Node node = nl.item(i);

    // again, you might want to check that .getChildNodes() doesn't return null
    // and that it is of type Node.Text
    firstnameList.add(node.getChildNodes()[0].getTextContent());
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.