2010-06-29 3 views
4

main 메소드를 실행할 때마다 a.xml의 이전 컨텐츠가 손실되어 새로운 메소드로 대체된다는 문제점이 있습니다. 이전 정보를 잃지 않고 a.xml 파일에 내용을 추가하는 방법?XStream을 사용하여 Java 객체를 XML로 직렬화

import java.io.FileNotFoundException; 
import java.io.PrintWriter; 

import com.thoughtworks.xstream.XStream; 
import com.thoughtworks.xstream.io.xml.DomDriver; 


public class Test { 
    public static void main(String[] args) throws FileNotFoundException { 
     XStream xs = new XStream(new DomDriver()); 
     Foo f = new Foo(1, "booo", new Bar(42)); 
     PrintWriter pw = new PrintWriter("a.xml"); 
     xs.toXML(f,pw); 
    } 
} 


public class Bar { 
    public int id; 

    public Bar(int id) { 
     this.id = id; 
    } 

} 


public class Foo { 
    public int a; 
    public String b; 
    public Bar boo; 
    public Foo(int a, String b, Bar c) { 
     this.a = a; 
     this.b = b; 
     this.boo = c; 
    } 
} 

답변

2

샘플 코드

public static void main(String a[]){ 
    //Other code omitted 
    FileOutputStream fos = new FileOutputStream("c:\\yourfile",true); //true specifies append 
    Foo f = new Foo(1, "booo", new Bar(42)); 
    xs.toXML(f,fos); 
} 
+0

대단히 감사합니다. –

3

질문은, 당신이 정말로 파일에 직렬화 된 XML 문자열을 추가 할하거나 XML 구조에 새로운 푸 인스턴스를 추가 할합니까.

대신
<foo> 
    <a>1</a> 
    <b>booo</b> 
    <bar> 
    <id>42</id> 
    </bar> 
</foo> 
<foo> 
    <a>1</a> 
    <b>booo</b> 
    <bar> 
    <id>42</id> 
    </bar> 
</foo> 

를 처음 분석하여 a.xml의 데이터를 보존 할 수 있습니다, 새로운 요소를 추가하고 직렬화 :

문자열을 기준으로 추가하면이 같은 대한 잘못된 XML 초래 전체 컬렉션/배열.

그래서 이런 걸 (Foo a.xml에서의 Collection 이미있는 가정) :

<foos> 
    <foo> 
    <a>1</a> 
    <b>booo</b> 
    <bar> 
     <id>42</id> 
    </bar> 
    </foo> 
    <foo> 
    <a>1</a> 
    <b>booo</b> 
    <bar> 
     <id>42</id> 
    </bar> 
    </foo> 
</foos> 
: 당신이의 라인을 따라 뭔가를 제공

List foos = xs.fromXml(...); 
foos.add(new Foo(1, "booo", new Bar(42))); 
xs.toXml(foos, pw); 

가 ...

HTH

+0

네, 그저하고 싶은 것입니다. 하지만 파일이 비어 있다면 어떨까요? 그러면 목록 foos = xs.fromXML (...)은 유효하지 않습니다. –

+0

몇 가지 특별한 경우를 처리해야합니다. 그러나 XStream에 따라 예외 또는 null을 얻습니다. 그런 다음 예외를 catch하거나 확인하여 계속 진행할 수 있습니다. –

+0

고마워요, 마틴 :) –

관련 문제