2012-05-15 47 views
0

我需要從xml文件中接收所有文本,以接收使用此代碼的特定標記。但我不知道如何解析來自XML的所有文本我的XML文件是不同的我不知道他們的根節點和子節點,但我需要單獨從XML文本。使用java dom從xml文檔單獨解析文本的可能方法

try { 

     DocumentBuilderFactory dbFactory = DocumentBuilderFactory 
       .newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(streamLimiter.getFile()); 
     doc.getDocumentElement().normalize(); 

     System.out.println("Root element :" 
       + doc.getDocumentElement().getNodeName()); 
     NodeList nList = doc.getElementsByTagName("employee"); 
     System.out.println("-----------------------"); 

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

      Node nNode = nList.item(temp); 
      if (nNode.getNodeType() == Node.ELEMENT_NODE) { 

       Element eElement = (Element) nNode; 

       NodeList nlList = eElement.getElementsByTagName("firstname") 
         .item(0).getChildNodes(); 

       Node nValue = (Node) nlList.item(0); 

       System.out.println("First Name : " 
         + nValue.getNodeValue()); 

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

回答

0

報價在這篇文章jsight's回覆:Getting XML Node text value with Java DOM

import java.io.ByteArrayInputStream; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 


class Test { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws Exception { 
    String xml = "<add job=\"351\">\n" 
     + " <tag>foobar</tag>\n" 
     + " <tag>foobar2</tag>\n" 
     + "</add>"; 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes()); 
    org.w3c.dom.Document doc = db.parse(bis); 
    Node n = doc.getFirstChild(); 
    NodeList nl = n.getChildNodes(); 
    Node an, an2; 

    for (int i = 0; i < nl.getLength(); i++) { 
     an = nl.item(i); 
     if (an.getNodeType() == Node.ELEMENT_NODE) { 
     NodeList nl2 = an.getChildNodes(); 

     for (int i2 = 0; i2 < nl2.getLength(); i2++) { 
      an2 = nl2.item(i2); 
      // DEBUG PRINTS 
      System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):"); 
      if (an2.hasChildNodes()) { 
      System.out.println(an2.getFirstChild().getTextContent()); 
      } 
      if (an2.hasChildNodes()) { 
      System.out.println(an2.getFirstChild().getNodeValue()); 
      } 
      System.out.println(an2.getTextContent()); 
      System.out.println(an2.getNodeValue()); 
     } 

     } 
    } 
    } 
} 

輸出:

#text: type (3): 
foobar 
foobar 
#text: type (3): 
foobar2 

適應這個代碼到你的問題,它應該工作。