2014-01-29 83 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 
}