2015-02-05 20 views
0

我有被註釋爲XMLType的提取XML譜寫的Java

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "fooClass", propOrder = { 
    "fooElement1", 
    "fooElement2" 
}) 
public class fooClass{ 
    @XmlElement(required = true) 
    protected String fooElement1; 

    @XmlElement(required = true) 
    protected String fooElement2; 

    ..... 

} 

我希望能夠提取XML表示的Java類(最好爲流,但字符串是OK以及)在Java中,沿線的東西:

fooClass foo = new fooClass() 
foo.setFooElement1("baba") 
foo.setFooElement2("abab") 

String xmlRep = DomSomething(foo) 

任何想法該怎麼辦?

謝謝!

+0

你或許應該創建一個JAXB背景下,看到這一點:http://www.mkyong.com/java/jaxb-hello-world-example/ – BretC 2015-02-05 16:54:59

回答

1

喜歡的東西:

try { 
    JAXBContext jaxbContext = JAXBContext.newInstance(fooClass.class); 
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    PrintStream ps = new PrintStream(baos); 
    jaxbMarshaller.marshal(fooInstance, ps); 

    String result = new String(baos.toByteArray()); 

    ... 
} catch (JAXBException e) { 
    ... 
} 
+0

創建JAXB上下文可以是昂貴的,你可能不希望這樣做每個電話... – BretC 2015-02-05 16:59:19

+0

我已經有JAXB內容創建以前,所以它可能是值得的 – jonatzin 2015-02-05 18:38:27

+0

這是行不通的,因爲fooClass沒有XMLRootElement,我不能添加一個,有沒有其他想法? – jonatzin 2015-02-06 15:29:42