2014-01-08 254 views
0

在用Java讀取XML文件之前,是否有必要完整地瞭解XML文件的結構和標籤?用Java讀取XML文件

areaElement.getElementsByTagName("checked").item(0).getTextContent() 

我在讀取文件之前不知道字段名「checked」。有什麼辦法可以列出XML文件中的所有標籤,基本上是文件結構?

+0

你可能會在這裏得到一些東西.. http://stackoverflow.com/questions/12255529/how-to-extract-xml-tag-value-without-using-the-tag-name-in-java – gowtham

回答

1

我已經自己準備好了這個DOM解析器,使用遞歸來解析你的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 RecDOMP { 


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\\ATT\\apip\\APIP_New.xml"))); 

// replace following path with your output xml path 
     File OutputDOM = new File("D:\\ambuj\\ATT\\apip\\outapip1.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(); 
    nodeValue=nodeValue.replace("\n","").replaceAll("\\s",""); 
    if (!nodeValue.isEmpty()) 
    { 
     System.out.println(nodeValue); 
     bw.write(nodeValue); 
     bw.newLine(); 
    } 
     } 
     visitRecursively(childNode,bw); 

      }   

    } 

} 
+0

謝謝你爲你的答案 – asjr

0

你一定要檢查出這個庫,如dom4j(http://dom4j.sourceforge.net/)。他們可以解析整個XML文檔,讓您不僅可以列出元素之類的東西,還可以在其上執行XPath查詢和其他如此酷炫的東西。

性能受到影響,特別是在大型XML文檔中,所以您需要在提交到庫之前檢查用例的性能。如果您只需要從XML文檔中取出一小部分內容(並且您知道您已經在查找什麼內容),則尤其如此。

0

您的問題的答案是否定的,沒有必要事先知道任何元素名稱。例如,您可以走樹來發現元素名稱。但這一切都取決於你實際想要做的事情。

對於絕大多數應用程序,順便說一句,Java DOM是解決問題的最糟糕的方法之一。但如果不知道您的項目需求,我不會進一步評論。