2012-06-08 4 views
1

나는 패션과 마찬가지로 toString()에 메소드를 작성하여 클래스 인스턴스의 XML 표현을 리턴한다고 생각했다. 아래에서 위로 클래스 인스턴스의 XML 표현을 만드시겠습니까?

먼저 나는

public Element toElement() { 
    // create Element instance and fill it 
} 

처럼 쓸 생각하지만 Element 창조는 createElement()의 전화 Document 인스턴스를 필요로하기 때문에 나는 빈 내부 Element 인스턴스를 만들 수 없습니다.

그래서 나는

public Element toElement(Document doc) { 
    Element ans = doc.createElement("myclasstag"); 

    // filling ans 

    return ans; 
} 

에 방법을 재 작성하지만이 상위 계층에 부착 될 때까지 하나 Element 인스턴스를 채울 수 없기 때문에 나는 런타임 예외 HIERARCHY_REQUEST_ERR을 얻었다.

그래서 나는

public Element toElement(Document doc, Element parent) { 

    Element ans = doc.createElement("myclasstag"); 
    parent.appendChild(ans); 

    // filling ans 

    return ans; 
} 

을 다음과 같은 방법을 다시 작성하는 것이었다 그러나이 방법은 내가 반환 할 필요가 없습니다 ANS 이미 연결되어 있기 때문에이 있어야 할 곳에, 그래서 지금은 어떤

public void append(Document doc, Element parent) { 

    Element ans = doc.createElement("myclasstag"); 
    parent.appendChild(ans); 

    // filling ans 
} 

되었다 절대적으로 싫어하는 toString().

toString()처럼 위에서 아래로 XML 인스턴스를 만들 수 있습니까?

+2

많은 일을 할 수 있습니다. 그래서 XStream이나 JAXB 같은 것이 존재하기 때문에 그렇게 할 필요가 없습니다. –

답변

1

XStream 사용하여, 나는이 작업을 수행 할 수 있습니다 :

package com.adarshr; 

import com.thoughtworks.xstream.XStream; 


class Parent { 
    private String name; 
    private int age; 

    public Parent(String name, int age) { 
     this.name = name; 
     this.age = age; 
    } 
} 

public class Test { 
    private Parent parent = new Parent("Abcd", 30); 

    public static void main(String[] args) throws Exception { 
     System.out.println(new Test()); 
    } 

    @Override 
    public String toString() { 
     return new XStream().toXML(this); 
    } 
} 

인쇄 어느 : 물론

<com.adarshr.Test> 
    <parent> 
    <name>Abcd</name> 
    <age>30</age> 
    </parent> 
</com.adarshr.Test> 

, 그것은 완벽하게 사용자 정의 할 수 있습니다.

관련 문제