2010-07-21 5 views
0

아래 예제 코드에서 노드를 DOM 문서에 연결하려고합니다. 1) 노드 "title, type"을 null로 초기화했습니다. 2) 위의 노드를 문서 "child_doc"에 추가하려고 시도한 다음이 노드에 새 값을 설정하려고했습니다.DOM 문서에 Null 값을 가진 노드 부착

위 내용을 수행 할 때 java.lang.NullPointerException이 발생합니다. child_doc.appendChild (title) .setNodeValue ("New"+ childType);

어떻게 해결할 수 있습니까?

감사합니다, 소니

예제 코드 :

public synchronized void attachNodeToParent1 (Element parent, String childType) throws ParserConfigurationException { 
     Document parent_doc = parent.getOwnerDocument(); 

     DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); 
     Document child_doc = docBuilder.newDocument(); 

     Element child = null; 
     Node title = null; 
     Node type = null;   
     child_doc.appendChild(title).setTextContent("New" + childType); 
     child_doc.appendChild(type).setTextContent(childType); 

     child = child_doc.getDocumentElement(); 

     parent.appendChild(child); 
    } 

답변

0

적절한 요소로 초기화 : 않는 코드의 각 라인을 가지고 항상 좋은 이유 @sony

Element title = child_doc.createElement("type"); 
Element type = child_doc.createElement("title); 
+1

입니다 한 가지만 한 가지. –

관련 문제