2014-08-31 3 views
0

XML 파일을 통해 구문 분석 중이므로 작동하는 자식 노드를 가져옵니다. 간단히 String에 넣고 for 루프에서 전달하려고하지만, 전달하면 String에 모든 자식 노드를 넣지 않고 String에 아무것도 넣지 않는 경우가 있습니다. if 문 아래에서 System.out.println (data)을 사용하면 제대로 작동합니다. if 루프에서 데이터를 가져 와서 전달하려고합니다. 여기에 내 코드 ...루프를 중첩 된 try-catch에서 문자열을 추출 할 수 없습니다.

public class Four { 

    public static void main(String[] args) { 

     Four four = new Four(); 
     String a = null; 
     try { 
      Document doc = four.doIt(); 
      String b = four.getString(doc); 

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

    } 

    public Document doIt() throws IOException, SAXException, ParserConfigurationException { 
     String rawData = null; 

     URL url = new URL("http://feeds.cdnak.neulion.com/fs/nhl/mobile/feeds/data/20140401.xml"); 
     URLConnection connection = url.openConnection(); 
     InputStream is = connection.getInputStream(); 
     Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); 

     return doc; 
    } 

    public String getString(Document doc) { 
     String data = null; 

     NodeList cd = doc.getDocumentElement().getElementsByTagName("game"); 
     for (int i = 0; i < cd.getLength(); i++) { 
      Node item = cd.item(i); 
      System.out.println("==== " + item.getNodeName() + " ===="); 
      NodeList children = item.getChildNodes(); 
      for (int j = 0; j < children.getLength(); j++) { 
      Node child = children.item(j); 


      if (child.getNodeType() != Node.TEXT_NODE) { 
       data = child.getNodeName().toString() + ":" + child.getTextContent().toString();  
       // if I System.out.println(data) here, it shows all everything 
       I want, when I return data it shows nothing but ===game=== 
      } 
     } 
     } 
     return data; 
    } 
} 
+0

값을 반환 할 때와 호출자가 값을 가져올 때 사이에 값을 변경해서는 안되기 때문에 디버거를 사용하여 디버깅을 시도 할 수 있습니까? –

답변

1

루프와 함께 try 문에서 발생하는 문제는 나타나지 않습니다. 그러나 getString 함수가 생각하는대로 작동하는지 확신 할 수 없습니다. 데이터를 할당하는 문을 자세히 살펴보십시오.

data = child.getNodeName().toString() + ":" + child.getTextContent().toString();  

루프의 각 반복마다 데이터 변수가 완전히 다시 할당됩니다. 반환 값에는 처리 된 마지막 노드의 데이터 만 포함됩니다.

아마도 당신이 의도 한 것은 노드의 값을 문자열의 끝에 연결하는 것입니다.

data += "|" + child.getNodeName().toString() + ":" + child.getTextContent().toString(); 
0

당신은 try 블록 외부 b을 정의해야합니다 수 있습니다 :

String b = null; 
    try { 
     Document doc = four.doIt(); 
     b = four.getString(doc); 

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

이것은 당신이 try 블록 외부의 값을 사용하게됩니다.

관련 문제