1

I only want to read the script tag from the given xml file.

testsuite.xml

 <?xml version="1.0" encoding="UTF-8" standalone="true"?>
                            -                                                                                                              
<TestSuite xsi:noNamespaceSchemaLocation="xyz.xsd" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  xmlns="http://www.example.org/TestSuite">   
  <Version>1.0.</Version> <Description>CETAF for Mobile</Description> 
  <C.E.T.A.FType>testSuite</C.E.T.A.FType>       
  <C.E.T.A.FName>CETAF</C.E.T.A.FName> <Init/> -<TestVector> -<Test> 
  <Script>TC1_LocalExec</Script>
  <Priority/> </Test> -<Test> 
  <Script>TC2_Remote</Script> <Priority/> </Test> -<Test>   
  <Script>TC3_DataDriven</Script> <Priority   </Test> -<Test> 
  <Script>TC4_PreConditionCheck</Script> <Priority/> </Test> -<Test>  
  <Script>TC5_PreConditionFail</Script> <Priority/> </Test> -<Test>    
  <Script>TC6_Host</Script> <Priority/> </Test> -<Test>   
  <Script>TC7_Deadlock</Script> <Priority/> </Test> -<Test>
  <Script>TC8_AdbTest</Script> <Priority/> </Test> -<Test> 
  <Script>TC9_AdbRemote</Script> <Priority/> </Test> </TestVector> </TestSuite>

My Code in Java is the following :

 package xmlparse;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.DocumentBuilder;
 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Node;
 import org.w3c.dom.Element;
 import java.io.File;
 public class ReadXMLFile {
 public static void main(String argv[]) {

     try {

         File fXmlFile = new File("/Users/388033/Desktop/KeplerWorkSpace_20140102/     KeplerWorkSpace/cetaf/Engine/TestFiles/TestSuite/TestSuite.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(fXmlFile);

         //optional, but recommended
         //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
         doc.getDocumentElement().normalize();

         System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

         NodeList nList = doc.getElementsByTagName("TestSuite");

         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {

             Node nNode = nList.item(temp);

             System.out.println("\nCurrent Element :" + nNode.getNodeName());

             if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                 Element eElement = (Element) nNode;

                 //System.out.println("Script : " + eElement.getAttribute("Script"));
                 System.out.println("Script : " + eElement.getElementsByTagName("Script").item(0).getTextContent());
                 System.out.println("Script : " + eElement.getElementsByTagName("Script").item(0).getTextContent());
                 //System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                 //System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                 //System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

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

But when I try this code, I only get the display for the 1st script. I would like to show every script, can you help me to find a way to do it.

Thanks.

splrs
  • 2,424
  • 2
  • 19
  • 29
user3148359
  • 21
  • 1
  • 2
  • 5

6 Answers6

1

Using DOM for this is a lot of work, you can do this much more easily using XPath. The expression to search for in your example would be

//Script/text()

which will get the element text for all Script tags regardless of where they are in the document.

The code needed is:

import org.w3c.dom.NodeList;
import org.xml.sax.*;
import javax.xml.xpath.*;

public class XPathTest {

    public static void main(String[] args) throws Exception {

        InputSource ins = new InputSource("c:/path/to/your/xmlfile.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList)xpath.evaluate("//Script/text()", ins, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            System.out.println(list.item(i).getNodeValue());
        }

    }
}
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

You need to add the index in your System.out statements as well. Right now you only print the first tag every time.

trappski
  • 1,066
  • 10
  • 22
0
                System.out.println("Script : " + eElement.getElementsByTagName("Script") .item(0) .getTextContent());
                System.out.println("Script : " + eElement.getElementsByTagName("Script") .item(0) .getTextContent());

You use 0 instead of index here

Make one more, inner cycle to run for all item's.

Gangnus
  • 24,044
  • 16
  • 90
  • 149
0

replace your for loop code with this:

for (int temp = 0; temp < nList.getLength(); temp++) {

    Node nNode = nList.item(temp);

    System.out.println("\nCurrent Element :" + nNode.getNodeName());

    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        Element eElement = (Element) nNode;

        //System.out.println("Script : " + eElement.getAttribute("Script"));
        System.out.println("Script : " + eElement.getElementsByTagName("Script").item(temp).getTextContent());
        System.out.println("Script : " + eElement.getElementsByTagName("Script").item(temp).getTextContent());
        //System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(temp).getTextContent());
        //System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(temp).getTextContent());
        //System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(temp).getTextContent());

    }
}
Fr_nkenstien
  • 1,923
  • 7
  • 33
  • 66
0

Here is a working code for your problem, just replace your xml file location in following code..... I have followed recursive approach here, so no need to know the tag name for parsing

  import java.io.BufferedWriter;
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
     import javax.xml.parsers.DocumentBuilder;  
     import javax.xml.parsers.DocumentBuilderFactory;  
     import org.w3c.dom.Document;  
     import org.w3c.dom.Node;  
     import org.w3c.dom.NodeList; 
    public class domTest29jan {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        dbf.setValidating(false); 
        DocumentBuilder db = dbf.newDocumentBuilder();   

// replace following  path with your input xml path  
         Document doc = db.parse(new FileInputStream(new File  ("D:\\ambuj\\29jan.xml")));  

// replace following  path with your output xml path 
         File OutputDOM = new File("D:\\ambuj\\29janoutapip1.txt");
            FileOutputStream fostream = new FileOutputStream(OutputDOM);
            OutputStreamWriter oswriter = new OutputStreamWriter (fostream);
            BufferedWriter bwriter = new BufferedWriter(oswriter);

            // if file doesnt exists, then create it
            if (!OutputDOM.exists()) {
                OutputDOM.createNewFile();}


            visitRecursively(doc,bwriter);
            bwriter.close(); oswriter.close(); fostream.close();

            System.out.println("Done");
}
public static void visitRecursively(Node node, BufferedWriter bw) throws IOException{  

             // get all child nodes  
         NodeList list = node.getChildNodes();                                  
         for (int i=0; i<list.getLength(); i++) {          
                 // get child node              
       Node childNode = list.item(i);  
       if (childNode.getNodeType() == Node.TEXT_NODE )
       {
   //System.out.println("Found Node: " + childNode.getNodeName()           
    //  + " - with value: " + childNode.getNodeValue()+" Node type:"+childNode.getNodeType()); 
   String nodeValue= childNode.getNodeValue();
   //System.out.println(childNode.getParentNode().getNodeName());
   nodeValue=nodeValue.replace("\n","").replaceAll("\\s","");
   if (!nodeValue.isEmpty() && childNode.getParentNode().getNodeName().equals("script"))
   {
       System.out.println(nodeValue);
       bw.write(nodeValue);
       bw.newLine();
   }
       }
       visitRecursively(childNode,bw);  

            }     

    }

}
kingAm
  • 1,755
  • 1
  • 13
  • 23
0

create class files to represent the XML file using annotations

@XMLRootElement
@XMLAttribute
@XMLElement

etc.

then use

MyCustomeClass xml = JAXB.unmarshal(new File("path to your xml file"), MyCustomeClass.class);

This will automatically populate the elements and attributes of the xml in the form of an object then you can use it as desired.

a part of your class structure can be :

@XmlRootElement
public class TestSuite {
    @XmlElement
    private String Version;

    @XmlElement
    private String   Description 
    .
    .
    .
    @XmlElement (name="TestVector")
    private TestVector testvector
}
Rohit Rehan
  • 568
  • 1
  • 4
  • 18