2014-01-29 84 views
1

我只想從給定的xml文件讀取腳本標記。使用java讀取xml文件

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> 

我的Java代碼如下:

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(); 
    } 
} 
} 

但當我嘗試這個代碼,我只得到了顯示的第一個腳本。 我想展示每一個腳本,你能幫我找到一個方法來做到這一點。

謝謝。

+0

嘗試http://xstream.codehaus.org/簡單,有用 –

回答

0

您還需要在System.out語句中添加索引。 現在你每次只打印第一個標籤。

0
   System.out.println("Script : " + eElement.getElementsByTagName("Script") .item(0) .getTextContent()); 
       System.out.println("Script : " + eElement.getElementsByTagName("Script") .item(0) .getTextContent()); 

您使用0而不是指數的這裏

作一次,內循環對所有項目的運行。

0

與此更換您的for循環代碼:

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()); 

    } 
} 
0

這裏是你的問題的工作代碼,只需更換您的XML文件的位置在下面的代碼..... 我已經在這裏跟着遞歸方法,所以沒有必要知道標記名稱解析

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); 

      }  

    } 

} 
1

使用DOM的,這是一個大量的工作,你可以使用XPath更容易做到這一點。表達式來搜索您的例子是

//Script/text() 

這將讓所有的腳本標籤元素文本,無論他們是在文檔中。

所需要的代碼是:

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()); 
     } 

    } 
} 
0

創建的類文件使用註釋

@XMLRootElement 
@XMLAttribute 
@XMLElement 

代表XML文件,然後使用

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

這會自動以對象的形式填充xml的元素和屬性,然後您可以根據需要使用它。

類結構的一部分,可以是:

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

    @XmlElement 
    private String Description 
    . 
    . 
    . 
    @XmlElement (name="TestVector") 
    private TestVector testvector 
}