2014-01-29 1 views
0
private void dislpay() { 
     try { 
      File fXmlFile = new File("/data/data/com.example.addnode/Add.xml"); 
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
      Document doc = dBuilder.parse(fXmlFile); 
      doc.getDocumentElement().normalize(); 
      System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
      NodeList nList = doc.getElementsByTagName("details"); 
      for (int temp = 0; temp <= nList.getLength(); temp++) { 
       Node nNode = nList.item(temp); 
       if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
        Element eElement = (Element) nNode; 

        String a=eElement.getElementsByTagName("firstname").item(temp).getTextContent().toString(); 
        String b=eElement.getElementsByTagName("lastname").item(temp).getTextContent().toString(); 
        String c=eElement.getElementsByTagName("nickname").item(temp).getTextContent().toString(); 

        System.out.println(a); 
        System.out.println(b); 
        System.out.println(c); 
       } 
      } 
      } catch (Exception e) { 
      e.printStackTrace(); 
      } 

XML입니다하는 값

<?xml version="1.0" encoding="UTF-8"?> 
    <user> 
     <details id="1"> 
     <firstname>JOHN</firstname> 
     <lastname>R</lastname> 
     <nickname>JJ</nickname> 
     </details> 
     <details> 
     <firstname>NOMAN</firstname> 
     <lastname>K</lastname> 
     <nickname>NK</nickname> 
     </details>  
    </user> 

예상 출력 :

JOHN R JJ 
NOMAN K NK 

전류 출력은 다음과 같습니다

JOHN R JJ 

내가 자식 노드의 모든 값을 표시 할 (세부 사항)하지만 응용 프로그램을 실행할 때 첫 번째 t 만 표시합니다. hree 값은 모두가 아닙니다. 저는 XML을 배우므로 XML에 대한 지식이 없습니다. 제발 날 안내해 줘.

답변

0
기존 코드에서

, 당신의 실수를 .... 수정, 사용자의 편의를 위해

//Remove = otherwise loop will run 3 times and you will get null pointer exception 
for (int temp = 0; temp < nList.getLength(); temp++) 

// Replace temp with 0 here because temp is increasing with your for loop and this is first node of this element always 

       String a=eElement.getElementsByTagName("firstname").item(0).getTextContent().toString(); 
       String b=eElement.getElementsByTagName("lastname").item(0).getTextContent().toString(); 
       String c=eElement.getElementsByTagName("nickname").item(0).getTextContent().toString(); 

, 나는 하나의 지식을하지 않고 XML을 구문 분석 재귀를 사용하여, 자신에 의해이 DOM 파서를 준비했다 꼬리표. 각 노드의 텍스트 내용이있는 경우 시퀀스로 제공합니다. 다음 코드에서 주석 처리 된 섹션을 제거하여 노드 이름을 가져올 수도 있습니다. 희망이 도움이 될 것입니다.

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

고맙습니다. –