XStream:
教程: http://www.studytrails.com/java/xml/xstream/xstream-introduction
示例代码结构:
.
├── XStreamExample.java
├── bean
│ ├── Address.java
│ └── Person.java
└── convert
└── SingleValueDateConverter.java
├── XStreamExample.java
├── bean
│ ├── Address.java
│ └── Person.java
└── convert
└── SingleValueDateConverter.java
package org.kanpiaoxue.learn.xstream; import org.kanpiaoxue.learn.xstream.bean.Address; import org.kanpiaoxue.learn.xstream.bean.Person; import com.google.common.collect.Lists; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Date; import java.util.List; /** * @ClassName: XStreamExample * @author kanpiaoxue * @version 1.0 * @CreateTime: 2019/04/03 10:25:51 * @Description: XStream示例类 * 官网: http://x-stream.github.io * 教程: * http://www.studytrails.com/java/xml/xstream/xstream-introduction/ */ public class XStreamExample { public static void main(String[] args) throws IOException { /** * <pre> * 警告信息:Security framework of XStream not initialized, XStream is probably vulnerable. * 原因分析:防止被攻击引起安全问题 * 参考资料: http://x-stream.github.io/security.html#example * 解决方案:设置安全策略和允许序列化和反序列的类型范围 * XStream.setupDefaultSecurity(xstream); * xstream.allowTypes(new Class[] { Person.class, Address.class }); * </pre> */ XStream xstream = new XStream(new DomDriver()); XStream.setupDefaultSecurity(xstream); xstream.allowTypes(new Class[] { Person.class, Address.class }); xstream.ignoreUnknownElements(); xstream.processAnnotations(Person.class); String country = "中国"; Address a1 = new Address(country, "北京市", "北京市", "海淀区", "中关村南大街1号"); Address a2 = new Address(country, "江苏省", "南京市", "无名区", "总统府大街1号"); List<Address> addresses = Lists.newArrayList(a1, a2); Person encodePerson = new Person(1, "薛", "仁", "贵", 70, addresses); encodePerson.setBirthday(new Date()); encodePerson.setName("helloWorld"); // 序列化 String xml = toXML(xstream, encodePerson); System.out.println(xml); // 反序列化 Person decodePerson = fromXML(xstream, xml); System.out.println(decodePerson); } private static Person fromXML(XStream xstream, String xml) throws IOException { /** * <pre> * 异常信息:Caused by: java.lang.AbstractMethodError: org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.setFeature(Ljava/lang/String;Z)V * 异常原因:在系统中存在着多个解析器的时候,这时候程序无法选择解析器。需要人工指定解析器。 * 解决方案:System.setProperty("javax.xml.parsers.DocumentBuilderFactory","com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); * </pre> */ System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); Person decodePerson = (Person) xstream.fromXML(xml); return decodePerson; } private static String toXML(XStream xstream, Person obj) throws IOException { try (Writer writer = new StringWriter()) { // 添加 xml 的 header writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); xstream.toXML(obj, writer); String xml = writer.toString(); return xml; } } }
package org.kanpiaoxue.learn.xstream.bean; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * @ClassName: Address * @author kanpiaoxue * @version 1.0 * @CreateTime: 2019/04/03 10:26:35 * @Description: 地址类 */ // 如果不给类起别名,则对应的是类包名,例:org.kanpiaoxue.learn.xstream.bean.Address @XStreamAlias("address") public class Address { private String country; private String province; private String city; private String street; private String houseNumber; /** * */ public Address() { super(); } /** * @param country * @param province * @param city * @param street * @param houseNumber */ public Address(String country, String province, String city, String street, String houseNumber) { super(); this.country = country; this.province = province; this.city = city; this.street = street; this.houseNumber = houseNumber; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Address other = (Address) obj; if (city == null) { if (other.city != null) { return false; } } else if (!city.equals(other.city)) { return false; } if (country == null) { if (other.country != null) { return false; } } else if (!country.equals(other.country)) { return false; } if (houseNumber == null) { if (other.houseNumber != null) { return false; } } else if (!houseNumber.equals(other.houseNumber)) { return false; } if (province == null) { if (other.province != null) { return false; } } else if (!province.equals(other.province)) { return false; } if (street == null) { if (other.street != null) { return false; } } else if (!street.equals(other.street)) { return false; } return true; } /** * @return the city */ public String getCity() { return city; } /** * @return the country */ public String getCountry() { return country; } /** * @return the houseNumber */ public String getHouseNumber() { return houseNumber; } /** * @return the province */ public String getProvince() { return province; } /** * @return the street */ public String getStreet() { return street; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((city == null) ? 0 : city.hashCode()); result = prime * result + ((country == null) ? 0 : country.hashCode()); result = prime * result + ((houseNumber == null) ? 0 : houseNumber.hashCode()); result = prime * result + ((province == null) ? 0 : province.hashCode()); result = prime * result + ((street == null) ? 0 : street.hashCode()); return result; } /** * @param city * the city to set */ public void setCity(String city) { this.city = city; } /** * @param country * the country to set */ public void setCountry(String country) { this.country = country; } /** * @param houseNumber * the houseNumber to set */ public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } /** * @param province * the province to set */ public void setProvince(String province) { this.province = province; } /** * @param street * the street to set */ public void setStreet(String street) { this.street = street; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } }
package org.kanpiaoxue.learn.xstream.bean; import org.kanpiaoxue.learn.xstream.convert.SingleValueDateConverter; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamOmitField; import java.util.Date; import java.util.List; /** * @ClassName: Person * @author kanpiaoxue * @version 1.0 * @CreateTime: 2019/04/03 10:26:25 * @Description: 人员类 */ // 如果不给类起别名,则对应的是类包名,例:org.kanpiaoxue.learn.xstream.bean.Person @XStreamAlias("person") public class Person { private Integer id; @XStreamAlias("first_name") private String firstName; @XStreamAlias("middle_name") private String middleName; @XStreamAlias("last_name") private String lastName; @XStreamAsAttribute private Integer age; private List<Address> addresses; @XStreamConverter(SingleValueDateConverter.class) private Date birthday; @XStreamOmitField private String name; /** * */ public Person() { super(); } /** * @param id * @param firstName * @param middleName * @param lastName * @param age * @param addresses */ public Person(Integer id, String firstName, String middleName, String lastName, Integer age, List<Address> addresses) { super(); this.id = id; this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; this.age = age; this.addresses = addresses; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Person other = (Person) obj; if (addresses == null) { if (other.addresses != null) { return false; } } else if (!addresses.equals(other.addresses)) { return false; } if (age == null) { if (other.age != null) { return false; } } else if (!age.equals(other.age)) { return false; } if (firstName == null) { if (other.firstName != null) { return false; } } else if (!firstName.equals(other.firstName)) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (lastName == null) { if (other.lastName != null) { return false; } } else if (!lastName.equals(other.lastName)) { return false; } if (middleName == null) { if (other.middleName != null) { return false; } } else if (!middleName.equals(other.middleName)) { return false; } return true; } /** * @return the addresses */ public List<Address> getAddresses() { return addresses; } /** * @return the age */ public Integer getAge() { return age; } /** * @return the birthday */ public Date getBirthday() { return birthday; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @return the id */ public Integer getId() { return id; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @return the middleName */ public String getMiddleName() { return middleName; } /** * @return the name */ public String getName() { return name; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addresses == null) ? 0 : addresses.hashCode()); result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((middleName == null) ? 0 : middleName.hashCode()); return result; } /** * @param addresses * the addresses to set */ public void setAddresses(List<Address> addresses) { this.addresses = addresses; } /** * @param age * the age to set */ public void setAge(Integer age) { this.age = age; } /** * @param birthday * the birthday to set */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * @param firstName * the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @param id * the id to set */ public void setId(Integer id) { this.id = id; } /** * @param lastName * the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @param middleName * the middleName to set */ public void setMiddleName(String middleName) { this.middleName = middleName; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } }
package org.kanpiaoxue.learn.xstream.convert; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import java.util.Date; /** * @ClassName: SingleValueDateConverter * @author kanpiaoxue * @version 1.0 * @CreateTime: 2019/04/03 11:14:03 * @Description: date的转换器 */ public class SingleValueDateConverter implements Converter { private static final DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); /* * (non-Javadoc) * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java.lang * .Class) */ @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return type.equals(Date.class); } /* * (non-Javadoc) * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object, * com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Date date = (Date) source; DateTime d = new DateTime(date); writer.setValue(d.toString(format)); } /* * (non-Javadoc) * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks. * xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { String str = reader.getValue(); DateTime d = format.parseDateTime(str); return d.toDate(); } }
输出内容:
xml:
<?xml version="1.0" encoding="UTF-8" ?> <person age="70"> <id>1</id> <first__name>薛</first__name> <middle__name>仁</middle__name> <last__name>贵</last__name> <addresses> <address> <country>中国</country> <province>北京市</province> <city>北京市</city> <street>海淀区</street> <houseNumber>中关村南大街1号</houseNumber> </address> <address> <country>中国</country> <province>江苏省</province> <city>南京市</city> <street>无名区</street> <houseNumber>总统府大街1号</houseNumber> </address> </addresses> <birthday>2019-04-03 11:42:56</birthday> </person>
json:
{ "id": 1, "firstName": "薛", "middleName": "仁", "lastName": "贵", "age": 70, "addresses": [ { "country": "中国", "province": "北京市", "city": "北京市", "street": "海淀区", "houseNumber": "中关村南大街1号" }, { "country": "中国", "province": "江苏省", "city": "南京市", "street": "无名区", "houseNumber": "总统府大街1号" } ], "birthday": "Apr 3, 2019 11:42:56 AM" }
JAXB:除了XStream之外,jdk也提供了类似的功能JAXB(Java Architecture forXMLBinding(JAXB))。
官网: Java Architecture for XML Binding,https://docs.oracle.com/javase/8/docs/technotes/guides/xml/jaxb/index.html
oracle提供的官网教程: https://docs.oracle.com/javase/tutorial/jaxb/intro/index.html
参考教程: https://www.baeldung.com/jaxb
举例如下:
public static void main(String[] args) throws IOException { String country = "中国====="; Address a1 = new Address(country, "北京市", "北京市", "海淀区", "中关村南大街1号"); Address a2 = new Address(country, "江苏省", "南京市", "无名区", "总统府大街1号"); List<Address> addresses = Lists.newArrayList(a1, a2); Person encodePerson = new Person(1, "薛", "仁", "贵", 70, addresses); encodePerson.setBirthday(new Date()); encodePerson.setName("helloWorld"); File file = new File( "hello.xml"); System.out.println(file); // 序列化 to file JAXB.marshal(encodePerson, file); Files.readAllLines(Paths.get(file.getAbsolutePath())).forEach(System.out::println); System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.parsers.SAXParser"); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); System.setProperty("javax.xml.parsers.SAXParserFactory", "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); // 反序列化 from file Person newPerson = JAXB.unmarshal(file, Person.class); System.out.println(newPerson); // 序列化 to String String xml = null; try (StringWriter writer = new StringWriter()) { JAXB.marshal(encodePerson, writer); xml = writer.toString(); System.out.println(xml); } // 反序列化 from String try (StringReader reader = new StringReader(xml)) { Person newPerson1 = JAXB.unmarshal(reader, Person.class); System.out.println(newPerson1); } }
相关推荐
总的来说,"基于java的转换xml.zip"可能是一个教学示例、一个小型项目或一个库,展示了如何利用XStream库在Java中高效、灵活地处理XML数据。通过学习和理解XStream的使用,开发者可以更好地处理XML数据交换,提升...
在提供的`xml-demo`压缩包中,可能包含了使用这两种方法的示例代码,通过查看和运行这些示例,你可以更好地理解如何在实际项目中应用XStream和JAXB进行XML与Java Bean的互转。无论选择哪种方法,都需要注意处理Java...
总的来说,"Java转换xml.rar"的资源可能包含使用XStream进行Java和XML转换的示例,这对于理解和实践Java中的XML处理非常有帮助。通过学习和掌握这一技术,开发者可以更高效地在Java应用中集成XML数据,实现数据的...
在"JsonDemo"这个示例中,可能包含了使用Java进行XML、JSON转换的代码实例,可能涵盖了上述提到的一些方法。通过阅读和学习这些代码,开发者可以更好地理解并掌握这些转换技巧,从而在实际项目中更加高效地处理数据...
XStream是Java平台上的一个开源库,它提供了一种简单且直观的方式来序列化和反序列化Java对象到XML,反之亦然。这个开发包“xstream.zip”包含的是XStream的特定版本——1.4.3-SNAPSHOT。 **XStream的核心功能:** ...
- **XStream:** 是一个轻量级、易于使用的库,支持将Java对象转换为XML,反之亦然,它提供了更简洁的API和更灵活的XML格式。 3. **DOM4J:** 这是一个非常流行的Java XML库,它扩展了DOM API,提供了一些额外的...
在Java编程中,将Java...总之,Java对象到XML的转换是一个重要的技能,理解不同的转换方法和库可以帮助我们更高效地处理数据交换和存储。在实际应用中,选择合适的工具和方法至关重要,以平衡性能、灵活性和易用性。
- 创建`JAXBContext`实例,它是JAXB的核心组件,负责处理Java类型和XML之间的转换。 - 使用`JAXBContext`的`createMarshaller()`方法创建`Marshaller`对象,然后调用`marshal()`方法,将Java对象转换为XML字符串或...
总的来说,这个“基于java的开发源码-转换xml.zip”可能包含了如何使用XStream进行XML和Java对象之间的转换的实际代码示例,对于学习或工作中处理XML数据的Java开发者来说,这是一个非常有价值的资源。通过深入理解...
为了方便地将Java对象与XML进行转换,开发者常常使用一些库,如XStream和Betwixt。这两个工具都提供了简单易用的API,帮助我们实现XML到对象(Object-to-XML)和对象到XML(XML-to-Object)的转换。 **XStream** ...
在IT行业中,XML(eXtensible Markup Language)和Java是两个非常重要的技术。XML是一种用于标记数据的语言,常用于...在提供的压缩包“Java转换xml源代码资料”中,你可能找到相关的示例代码和教程,进一步加深理解。
JAXB是Java平台的标准部分,提供了自动化的对象到XML和XML到对象的转换。 - **JAXB**:使用JAXB,我们首先需要为Bean类创建对应的XML绑定(JAXB annotations)。这些注解如`@XmlRootElement`、`@XmlElement`等,...
6. **其他库**:除了JAXB,Java还有其他库可以实现XML到Object的转换,例如Apache的`XStream`和Google的`Gson`。这些库提供了不同的功能和性能,可以根据项目需求选择。 7. **性能优化**:对于大型XML文件,可以...
在提供的文件`ClassToXml.java`和`CC.java`中,很可能是实现了XML到Bean或Bean到XML转换的示例代码。具体实现细节需要查看源代码才能理解。通常,这些类会包含对JAXB API的调用,如创建JAXBContext、Unmarshaller和...
1. **JAXB(Java Architecture for XML Binding)**:JAXB是Java平台的标准部分,允许我们在Java对象和XML之间进行自动转换。要使用JAXB,你需要在Model类上添加一些注解,如`@XmlRootElement`,`@XmlElement`等,...
- **与 JAXB**:虽然两者都可以将 Java 对象转换为 XML,但 JAXB 更侧重于基于注解的自动绑定,而 XStream 提供了更多的控制权和灵活性。 深入研究 XStream 的源码,开发者可以学习到如何利用反射、流处理和类型...
Java提供了多种库来处理XML,例如JAXB(Java Architecture for XML Binding)、DOM(Document Object Model)、SAX(Simple API for XML)和StAX(Streaming API for XML)。但是,这里我们关注的是XStream库,它是...
此外,还有许多库如JAXB(Java Architecture for XML Binding)和XStream,它们提供了更高级别的抽象,使得XML操作更为简便。不过,理解基础的DOM、SAX和StAX仍然是必要的,因为它们构成了许多高级库的基础。
另外,Spring框架中的`org.springframework.oxm`包提供了多种XML转换工具,如JAXB、Castor、XStream等,可以方便地进行XML与Java对象之间的转换。 总结起来,Java中的XML处理是一项重要的技能,涵盖DOM、SAX、StAX...
7. **替代方案**:随着技术的发展,如JAXB(Java Architecture for XML Binding)和XStream等工具也提供了类似的功能,它们可能更适合处理现代的XML映射需求。 8. **最佳实践**:在使用Castor时,建议保持XSD文件的...