gpt4 book ai didi

java - 带对象的 Xml 序列化器和反序列化器

转载 作者:行者123 更新时间:2023-11-29 06:16:41 24 4
gpt4 key购买 nike

在 Dot Net XmlSerializer 对象到 xml 和 Deserializer 中将 xml 标签转换为对象 --在 Java 中如何做?

public static object ConvertToObject(Type objectType,String strxml)
{
try
{
Object obj=null;
XmlSerializer xs=new XmlSerializer(objectType);
obj=xs.Deserializer(new StringReader(strxml));
return obj;
}
catch(Exception e)
{
}

//Xml serialized with ihuti java and converted to xml by argobj
public static object ConvertFromObject(ihutidata argobj)//ihuti.java with xml elements
{
try
{
XmlWriterSettings Sett=new XmlWritterSettings();
settings.OmitXmlDeclaration=true;

StringBuilder builder=new StringBuilder();
XmlSerializer xs=new XmlSerializer(typeof(ihutidata));
XmlWriter xw=XmlWriter.Create(builder,settings);

xs.Serialize(xw,argobj);
xw.close();

return (builder.ToString());
}
catch(Exception e)
{
return("Exception"+e);
}
internal string savetodb(TSring argdata,string argclientip)
{
ihutidata req=(ihutidata)DataProcessing.ConvertToObject(typeof(ihutidata),argdata);

if(req!=null)
{
......
......
}
}

ya 我同意 XStream 它将 xml 转换为对象,反之亦然,但我的问题是......我必须用类调用 converttoobject() 并将其作为对象传递。由于程序保留在 C# 中,所以我在 Java 中执行相同的过程。

ihutidata是一个包含xml根元素、属性和元素等的类。在 Java 中可能吗?

最佳答案

有很多库可以完成这项工作(序列化和反序列化对象),最简单的使用之一是 XStreamhere 是使用的示例:

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

现在您可以简单地运行 String xml = xstream.toXML(joe); 结果是:

<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>

要返回对象运行 Person newJoe = (Person)xstream.fromXML(xml);

另一个可能的选择是 JAXB ,来自 wikipedia :

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program's class structure. It is similar to xsd.exe and xmlserializers in .Net Framework.

但对我来说,大多数任务都可以使用 XStream 完成,它轻巧且更容易(恕我直言)

关于java - 带对象的 Xml 序列化器和反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4836032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com