使用java读取xml文件

时间:2014-01-29 10:36:50

标签: java xml

我只想从给定的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();
    }
}
}

但是当我尝试这段代码时,我只得到第一个脚本的显示。 我想展示每个剧本,你能帮我找到办法吗?

感谢。

6 个答案:

答案 0 :(得分:1)

使用DOM做了很多工作,使用XPath可以更轻松地完成这项工作。要在您的示例中搜索的表达式为

//Script/text()

将获取所有Script标记的元素文本,无论它们在文档中的位置如何。

所需的代码是:

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

    }
}

答案 1 :(得分:0)

您还需要在System.out语句中添加索引。 现在你每次只打印第一个标签。

答案 2 :(得分:0)

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

你在这里使用0而不是索引

为所有项目再做一个内部循环。

答案 3 :(得分: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());

    }
}

答案 4 :(得分: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);  

            }     

    }

}

答案 5 :(得分:0)

使用注释创建类文件以表示XML文件

@XMLRootElement
@XMLAttribute
@XMLElement

然后使用

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
}