以有效的方式将 XML 解析为 JAVA POJO
Posted
技术标签:
【中文标题】以有效的方式将 XML 解析为 JAVA POJO【英文标题】:Parse XML TO JAVA POJO in efficient way 【发布时间】:2013-01-25 04:57:28 【问题描述】:如何有效地为下面的xml解析和创建java pojo?请推荐任何有效的解析器。
XML格式是
<?xml version="1.0" encoding="utf-8"?>
<CCMainRootTag ID="12">
<Header TableName="TableName" TableVersion="12" TableID="12" CreatedDate="2013-02-09T15:35:33" CreatedByUserName="ABC" CreatedBySystem="ABC" />
<ClassPrimary ID="12" Code="Y" DescriptionDK="DK language " DescriptionUK="" DefDK="" DefUK="" IFDGUID="">
<ObjectClass ID="12" Code="YA" DescriptionDK="DK Language" DescriptionUK="" DefDK="" DefUK="" IFDGUID="">
<Synonym>
<Concept Description="Description" Language="DK" />
<Concept Description="" Language="UK" />
<Concept Description="Description" Language="DK" />
<Concept Description="" Language="UK" />
<Concept Description="Description" Language="DK" />
<Concept Description="" Language="UK" />
<Concept Description="Description" Language="DK" />
<Concept Description="" Language="UK" />
</Synonym>
</ObjectClass>
<ObjectClass ID="12" Code="YB" DescriptionDK="DK Language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
<ObjectClass ID="12" Code="YC" DescriptionDK="DK Language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
<ObjectClass ID="12" Code="YD" DescriptionDK="DK language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
</ClassPrimary>
</CCMainRootTag>
我已经在使用 thisLink,但是它的性能很慢,并且有问题并没有有效的 pojo。
我想以一种有效的方式为我提供直接 java pojo 的解析器。
【问题讨论】:
【参考方案1】:您可以使用JAXB 将 XML 转换为 Java POJO。但在您最终确定解决方案之前check this site 进行性能比较。
【讨论】:
您好 CuriousMind,但在我的情况下,xml 属性将是类变量。参见这个例子。 TableName="TableName" TableVersion="12" TableID="12" CreatedDate="2013-02-09T15:35:33" CreatedByUserName="ABC" CreatedBySystem="ABC" /> 如何为这种类型定义 xml pojo结构。? JAXB 为您提供注释以将属性绑定到类变量。查看 JAXB 文档站点了解更多详细信息。【参考方案2】:对于那些正在寻找将 xml 转换为 java 对象的 JAXB 代码的人:
//Convert xml to String first
Element partyLoaderRequest; // your xml data
String xmlString = new XMLOutputter().outputString(partyLoaderRequest);
InputStream is = new ByteArrayInputStream(xmlString.getBytes());
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = docBuilder.parse(is);
org.w3c.dom.Element varElement = document.getDocumentElement();
JAXBContext context = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<Person> loader = unmarshaller.unmarshal(varElement, Person.class);
Person inputFromXml = loader.getValue();
而 Person 有适当的 XML 注释:
@XmlRootElement(name="Person")
public class CimbWlAdminUserAmendInput
@XmlElement(name="companyName",required=true,nillable=false)
private String companyName;
...
//setters getters
@XmlTransient
public String getCompanyName()
return companyName;
public void setCompanyName(String companyName)
this.companyName = companyName;
【讨论】:
【参考方案3】:序列化和反序列化可以由 JacksonXmlModule 处理。
// Item.class - use lombok or create g/setters
@JsonPropertyOrder("name", "description", "note")
public class Item
private String name;
private String description;
private String note;
// Test.class
package hello.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import hello.entity.Item;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class NameServiceImplTest
ObjectMapper objectMapper;
@Before
public void setup()
JacksonXmlModule xmlModule = new JacksonXmlModule();
xmlModule.setDefaultUseWrapper(false);
this.objectMapper = new XmlMapper(xmlModule);
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
@Test
public void serializeTest()
// Wrapper
@JacksonXmlRootElement(localName = "names")
class Names
public List<Item> item = new ArrayList<>();
Item item = new Item();
item.setName("Vladimir");
item.setDescription("Desc");
item.setNote("Note");
Item item2 = new Item();
item2.setName("Iva");
item2.setDescription("Desc2");
item2.setNote("Note2");
Names names = new Names();
names.item.add(item);
names.item.add(item2);
try
String xml = objectMapper.writeValueAsString(names);
assertNotNull(xml);
System.out.println(xml);
catch (Exception e) // IOException
System.out.println(e.getMessage());
fail();
@Test
public void deserializeTest()
String xml = "<names>" +
"<item><name>name</name><description>desc</description><note>note</note></item>" +
"<item><name>name</name><description>desc</description><note>note</note></item>" +
"</names>";
try
List<Item> names = objectMapper.readValue(xml, new TypeReference<List<Item>>() );
names.forEach(item ->
assertEquals("name", item.getName());
assertEquals("desc", item.getDescription());
assertEquals("note", item.getNote());
);
catch (Exception e) // IOException
【讨论】:
【参考方案4】:public class XmlConvertUtil
public static void main(String[] args)
ResultDataSet resultDataSet = new ResultDataSet(new DtInformation("0", "Success"), new DtData("980000001"));
//Method which uses JAXB to convert object to XML
System.out.println(JaxbObjToXML(resultDataSet));
public static Object JaxbXmlToObj(String xmlString, Object obj)
JAXBContext jaxbContext;
try
jaxbContext = JAXBContext.newInstance(obj.getClass());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Object resultDataSet = (Object) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
//System.out.println(resultDataSet);
catch (JAXBException e)
e.printStackTrace();
return obj;
public static String JaxbObjToXML(Object object)
String xmlContent = null;
try
//Create JAXB Context
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
//Create Marshaller
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//Required formatting??
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
//Print XML String to Console
StringWriter sw = new StringWriter();
//Write XML to StringWriter
jaxbMarshaller.marshal(object, sw);
//Verify XML Content
xmlContent = sw.toString();
//System.out.println(xmlContent);
catch (JAXBException e)
e.printStackTrace();
return xmlContent;
【讨论】:
嘿,谢谢你的回答。你也能解释一下吗?以上是关于以有效的方式将 XML 解析为 JAVA POJO的主要内容,如果未能解决你的问题,请参考以下文章
Java - 将xml转换为JAVA Pojo类,包括java注释(Simplexml)
如何将查询的结果集转换为可以进一步解析以创建json的pojo类?