<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="age" type="xs:int"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> public class Person { private String name; private int age; // getters and setters } <binding> <mapping name="PersonMapping" class="com.example.Person"> <structure map-as="person" name="person"> <value name="name" field="name"/> <value name="age" field="age"/> </structure> </mapping> </binding> IBindingFactory bindingFactory = BindingDirectory.getFactory(Person.class); IMarshallingContext marshallingContext = bindingFactory.createMarshallingContext(); Person person = new Person(); person.setName("John"); person.setAge(25); StringWriter writer = new StringWriter(); marshallingContext.setOutput(writer); marshallingContext.marshalDocument(person); String xml = writer.toString(); System.out.println(xml); IBindingFactory bindingFactory = BindingDirectory.getFactory(Person.class); IUnmarshallingContext unmarshallingContext = bindingFactory.createUnmarshallingContext(); String xml = "<person><name>John</name><age>25</age></person>"; StringReader reader = new StringReader(xml); unmarshallingContext.setInput(reader); Person person = (Person) unmarshallingContext.unmarshalDocument(); System.out.println(person.getName()); System.out.println(person.getAge());


上一篇:
下一篇:
切换中文