반응형
출처: http://kr.blog.yahoo.com/kwon37xi/folder/3381246.html

  • DOM은 XML을 생성하고 변경할 수 있다.

XML DOM 트리의 생성과 변경

  • 새로운 XML을 생성하기 위해서는 org.w3c.dom.DOMImplementation을 구현한 클래스를 사용해야한다.
  • Xerces의 DOMImplementation구현 : org.apache.xerces.dom.DOMImplementationImpl
  • 생성 예

    DOMImplementation domImpl = new DOMImplementationImpl();
    Document doc = domImpl.createDocument(null, "rootElement", null);
    
  • Document 객체 생성시 파서의 Document 구현 클래스를 사용하면 DocType 이 생성되지 않는다. DOMImplementation 을 사용해서 새로운 XML DOM 트리를 생성해야 한다.
  • DOMImplementation.createDocument(1,2,3);
    • 첫번째 인자 : 문서의 루트 요소를 위한 네임스페이스
    • 두번째 인자 : 루토 요소
    • 세번째 인자 : DocType 클래스의 인스턴스.
  • DocType이 필요할 경우 DOMImplementation.createDocType() 사용.
  • 변경 예

    Element root = doc.getDocumentEelment();
    root.setAttribute("id", id); // id 속성의 추가
    
    Element nameElement = doc.createElement("name");
    Text nameText = doc.createTextNode("내용");
    nameElement.appendChild(nameText); //name 요소에 텍스트 값 추가
    root.appendChild(nameElement); // rootElement 요소에 name 요소 추가
    
  • 모든 노드의 생성은 Document 객체의 create* 메소드를 통해서 이뤄진다.
  • "appendChild()"는 자식 노드를 추가한다.

네임스페이스

  • DOM Level 2는 네임스페이스를 지원한다.
  • 네임스페이스를 위해 Node 인터페이스는 "getPrefix()"와 "getNamespaceURI()" 메소드를 제공한다.
  • Document.createElementNS() 네임스페이스를 지원하는 요소 추가.
  • 네임스페이스를 인식하는 각 메소드의 첫번째 인자는 "네임스페이스 URI"이고, 두번째 인자는 요소와 속성등의 QName이다. QName은 "ora:copyright" 와 같은 형태를 띈다.
  • "ora:copyright" 요소에서 getPrefix() : "ora" 리턴
  • 네임스페이스에 속하지 않는 요소에서 getPrefix() : null 리턴
  • 네임스페이스를 지정했을 때는 루트 요소에 xmlns 속성을 지정해야 한다.

DOM Level 2 - 순회(Traverse)

  • DOM 트리를 순회하는 기능을 제공한다.
  • "org.w3c.dom.traversal.DocumentTraversal" 인터페이스를 이용한다.
  • 일반적인 파서의 Document 구현 클래스는 DocumentTraversal 도 함께 구현한다.
  • NodeIterator

    NodeList descriptionElements =
    	root.getElementsByTagNameNS(docNS, "description");
    Element description = (Element)descriptionElements.item(0);
    
    // NodeIterator를 구한다.
    NodeIterator i = ((DocumentTraversal)doc)
    	.createNodeIterator(description, NodeFilter.SHOW_ALL,
    	new FormattingNodeFilter(), true);
    
    Node n;
    
    while ((n = i.nextNode()) != null) {
    	System.out.println("Search phrase found: '" + n.getNod eVal  ue() + "'");
    }
    
  • createNodeIterator(1, 2, 3, 4)
    • 첫번째 인자 : 순회할 노드 요소
    • 두번째 인자 : 상수 필터
      1. NodeFilter.SHOW_ALL : 모든 노드를 포함하여 순회
      2. NodeFilter.SHOW_ELEMENT : 요소만 순회
      3. NodeFilter.SHOW_TEXT : 텍스트 노드만 순회
    • 세번째 인자 : NodeFilter 구현 객체
    • 네번째 인자 : 엔티티 참조의 실제값을 분석할 것인가?
    • 두번째와 세번째 인자가 함께 나올 경우 두번째 인자 필터를 우선적용하고 그 결과를 다시 세번째 인자로 필터링한다.
  • NodeFilter
    • public short acceptNode(Node n); 을 이용해서 순회할 노드인지 여부를 결정한다.
      • 리턴값 NodeFilter.FILTER_SKIP : 필터로 들어온 노드는 건너 뛰고 그 자식노드를 계속 탐색
      • 리턴값 NodeFilter.FILTER_REJECT : 필터로 들어온 노드와 그 자식 모두 건너 뜀
      • 리턴값 NodeFilter.FILTER_ACCEPT : 필터로 들어온 노드 사용
    • 노드 필터 예

      class FormattingNodeFilter implements NodeFilter {
      	public short acceptNode(Node n) {
      		if (n.getNodeType() == Node.TEXT_NODE) {
      			Node parent = n.getParentNode();
      
      			if ((parent.getNodeName().equalsIgnoreCase("b")) ||
      				(parent.getNodeName().equalsIgnoreCase("i"))) {
      				return FILTER_ACCEPT;
      			}
      		}
      
      		return FILTER_SKIP;
      	}
      }
      
  • TreeWalker
    트리 뷰를 얻는다. 필터를 이용해 특정한 요소 등만 가진 트리를 생성해낸다.

범위(Range)

알 수 없는 DOM 구조에 새로운 컨텐트를 추가하거나 또는 컨텐트를 삭제, 복사, 추출해야 할 경우에 범위 모듈을 사용한다.

Wrong document Exception

잘못된 문서 예외(Wrong document Exception)은 서로 다른 문서의 노드들을 함께 사용하려 할 때 발생한다.

다른 문서의 노드를 현재 문서에 append하려면 importNode를 사용한다.
Element otherDocElement = otherDoc.getDocumentElement();
Element thisDocElement = thisDoc.getDocumentElement();

// 대상 문서에 노드 임포트
Element readyToUseElement =
    (Element)thisDoc.importNode(otherDocElement);

// 아무문제없이 노드 추가
thisDocElement.appendChild(readyToUseElement);



+ Recent posts