2010-11-26 3 views
3

자식 노드 목록을 반복하여 Collada XML 파일을 읽으려고하고 있으며 다른 모든 출력은 #text를 읽습니다. 무엇에 대한 거지? 내 코드 :XML 및 DOM 출력 #text 출력

public void runTest() { 
    File file = new File("test.dae"); 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = null; 
    try { 
     builder = factory.newDocumentBuilder(); 
    } 
    catch(ParserConfigurationException error) { 
     System.out.println("--ParserConfigurationException: " + error.getMessage()); return; 
    } 
    Document document = null; 
    try { 
     document = builder.parse(file); 
    } 
    catch(IOException error) { 
     System.out.println("--IOException: " + error.getMessage()); return; 
    } 
    catch(SAXException error) { 
     System.out.println("--SAXException: " + error.getMessage()); return; 
    } 
    Node node = document.getDocumentElement(); 
    String node_name = node.getNodeName(); 
    System.out.println(node_name); 
    NodeList node_list = node.getChildNodes(); 
    for(int iterator = 0; iterator < node_list.getLength(); iterator++) { 
     Node child_node = node_list.item(iterator); 
     String child_node_name = child_node.getNodeName(); 
    System.out.println("-- " + child_node_name); 
    } 
} 

답변

4

"하는 #text는"단순히 텍스트 노드의 getNodeName와() 메서드를 호출의 결과입니다. (org.w3c.dom.Node에 대한 API 문서를 보면 알 수 있듯이) 노드의 실제 텍스트 내용을 원한다면 getNodeValue() 메소드를 사용하면된다.

텍스트 노드가 없을 것으로 예상되는 경우 개행 문자와 같은 작은 공백 문자도 텍스트로 처리된다는 점을 잊지 마십시오.

+1

흠. 텍스트 노드에 텍스트가 있기를 기대합니다. 방금 getNodeName()이 노드 이름을 얻는 것 외에는 아무것도하지 않을 것이라고 생각하지 않았습니다. 여기 그것이 달빛처럼 getNodeType()이나 뭐든간에 보인다. 어쨌든, 나는 왜 그런지에 대해서는 의문의 여지가 없습니다, 좋은 이유가있을 것입니다. 현재로서는 if (node_name == "#text")와 같은 코드를 추가해야합니다. 내가 원하는 걸 얻기 위해서. – Espen

+0

나중에 참조 할 수 있도록 요소를 가져 오는 더 좋은 방법이 있습니다. 'Element' 인터페이스의'getElementsByTagName' 메소드를 확인하십시오. 'getElementsByTagName ("*")'를 사용하면 주어진 엘리먼트의 자식 엘리먼트를 얻을 수있다. NodeList를 살펴보면'Element'에 캐스트가 필요하지만, 그만한 가치가 있습니다. – fakedad