2012-05-07 1 views
0

에서 생성 된 XML 파일의 첫 번째 줄과 같은 임의의 텍스트를 작성 :JAXB는 내 생성 된 XML 파일에서 다른 객체와 현재의 내 콘솔 출력을 마샬링하는 JAXB를 사용하고 스트림

<Cat> 
    <name>Toby</name> 
</Cat> 

나는 Cat.xml 내에서 생성되어 일치하는 콘솔의 출력은 그러나 이러한 경우가 예상된다. 제 질문은 "올바른"Cat.xml을 생성하기위한 나의 접근 방식에서 잘못된 것인가요? 아래 최소 기능 프로그램 :

public class CatDriver{ 
public static void main(String[] args) throws JAXBException, IOException, 
      ParserConfigurationException, TransformerException { 

     Cat cat = new Cat(); 
     cat.setName("Toby"); 
     JAXBContext context = JAXBContext.newInstance(Cat.class); 

     Marshaller m = context.createMarshaller(); 
     m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); 
     m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
     m.setProperty(
       "com.sun.xml.bind.xmlHeaders", 
       "<!-- My awesome comment" 
         + " --> \n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); 
     m.marshal(cat, System.out); 
     Writer w = null; 
     try { 
      w = new FileWriter("C:/test/Cat.xml"); 
      m.marshal(cat, w); 

     } finally { 
      try { 
       w.close(); 
      } catch (Exception e) { 
      } 
     } 

    } 
} 

@XmlRootElement(name = "Cat") 
class Cat { 
    private String name; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

답변

-1
Cat cat = new Cat(); 
cat.setName("Toby"); 
JAXBContext context = JAXBContext.newInstance(Cat.class); 

Marshaller m = context.createMarshaller(); 
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE); 

m.marshal(cat, System.out); 
Writer w = null; 
try 
{ 
    w = new FileWriter("Cat.xml"); 
    w.append("<!-- My awesome comment -->"); 
    w.flush(); 
    m.marshal(cat, w); 

} 
finally 
{ 
    try 
    { 
    w.close(); 
    } 
    catch (Exception e) 
    { 
    } 
} 
+0

예를 들어주세요. 특히 기본 생성자가 없으므로 특히 그렇습니다. – Woot4Moo

+0

@ Woot4Moo 콘솔에서 작동하는 경우 파일에서도 작동합니다. 유일한 차이점은 이미 마샬 러를 한 번 사용한 점입니다. 그래서 context.createMarshaller(); 파일에 쓰기 전에 두 번째 어쨌든 태양 특정 속성을 사용하는 것은 나에게 좋은 생각이 아닌 것 같습니다. JAXB_Fragment를 false로두고 파일 작성자에게 직접 주석을 쓰지 않는 이유는 무엇입니까? – Omnaest

+0

JAXB는이를 수행하는 방법을 보여주기 때문에. 또한 system.out에 대한 호출을 제거해도 문제가 해결되지 않았습니다. – Woot4Moo

관련 문제