[英]Issue regarding Java to XML conversion and vice versa
我有這樣的XML,我從中間件獲得
<Example library="somewhere">
<book>
<AUTHORS_TEST>Author_Name</AUTHORS_TEST>
<EXAMPLE_TEST>Author_Name</EXAMPLE_TEST>
</book>
</Example>
我想做的是將XML轉換為Java對象(反之亦然):
class Example
{
private String authorsTest;
private String exampleTest;
}
所以有什么辦法可以映射這兩者,需要注意的是XML Tag Name和Class屬性名是不同的,所以有人可以建議以最小的更改實現它嗎?Xstream是一個不錯的選擇,但是如果我有很多字段的數量將很難添加別名,因此除了XStream之外還有其他更好的選擇嗎?
有很好的庫可以為您完成此任務。 一個簡單的例子就是XStream 。
請參閱兩分鍾教程中的以下示例 :
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
現在,要將其轉換為XML,您要做的就是簡單地調用XStream:
String xml = xstream.toXML(joe);
生成的XML如下所示:
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</person>
我更喜歡XStream,因為它非常易於使用。 如果您想做更復雜的事情,例如從XML生成Java類,您應該看看Miquel提到的JAXB 。 但這更復雜,需要更多時間才能開始。
您正在尋找的被稱為XML綁定,您實際上在其中將xml轉換為基於xml模式的java類。 對此的參考實現是jaxb,但還有許多其他選擇。
注意:我是EclipseLink JAXB(MOXy)的負責人,並且是JAXB 2(JSR-222)專家組的成員。
大多數XML綁定庫在XML表示形式的每層嵌套中都需要一個對象。 EclipseLink JAXB(MOXy)具有@XmlPath
擴展名,該擴展名使基於XPath的映射可以消除此限制。
例
以下演示了如何將@XmlPath
擴展應用於您的用例。
package forum10511601;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name="Example")
@XmlAccessorType(XmlAccessType.FIELD)
class Example {
@XmlAttribute
private String library;
@XmlPath("book/AUTHORS_TEST/text()")
private String authorsTest;
@XmlPath("book/EXAMPLE_TEST/text()")
private String exampleTest;
}
jaxb.properties
要將MOXy指定為JAXB提供程序,需要在與域模型相同的包中添加一個名為jaxb.properties
的文件,並帶有以下條目(請參閱將EclipseLink MOXy指定為JAXB提供程序 )。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示版
由於MOXy是JAXB(JSR-222)的實現,因此您將使用標准的JAXB運行時API(從Java SE 6開始包含在JRE / JDK中)。
package forum10511601;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Example.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10511601/input.xml");
Example example = (Example) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(example, System.out);
}
}
input.xml /輸出
<?xml version="1.0" encoding="UTF-8"?>
<Example library="somewhere">
<book>
<AUTHORS_TEST>Author_Name</AUTHORS_TEST>
<EXAMPLE_TEST>Author_Name</EXAMPLE_TEST>
</book>
</Example>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.