C# 将对象转换为 XML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11447529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an object to an XML string
提问by FluepkeSchaeng
I have got a class named WebserviceTypeI got from the tool xsd.exe from an XSD file.
我有一个名为WebserviceTypeI 从 XSD 文件中的工具 xsd.exe获得的类。
Now I want to deserialize an instance of an WebServiceTypeobject to a string.
How can I do this?
现在我想将一个WebServiceType对象的实例反序列化为一个字符串。我怎样才能做到这一点?
The MethodCheckTypeobject has as params a WebServiceTypearray.
该MethodCheckType对象具有作为参数的WebServiceType数组。
My first try was like I serialized it: with a XmlSerializerand a StringWriter(while serializing I used a StringReader).
我的第一次尝试就像我对其进行了序列化:使用 aXmlSerializer和 a StringWriter(在序列化时我使用了 a StringReader)。
This is the method in which I serialize the WebServiceTypeobject:
这是我序列化WebServiceType对象的方法:
XmlSerializer serializer = new XmlSerializer(typeof(MethodCheckType));
MethodCheckType output = null;
StringReader reader = null;
// catch global exception, logg it and throw it
try
{
reader = new StringReader(path);
output = (MethodCheckType)serializer.Deserialize(reader);
}
catch (Exception)
{
throw;
}
finally
{
reader.Dispose();
}
return output.WebService;
Edit:
编辑:
Maybe I could say it in different words: I have got an instance of this MethodCheckTypeobject an on the other hand I have got the XML document from which I serialized this object. Now I want to convert this instance into a XML document in form of a string. After this I have to proof if both strings (of XML documents) are the same. This I have to do, because I make unit tests of the first method in which I read an XML document into a StringReaderand serialize it into a MethodCheckTypeobject.
也许我可以换一种说法:我有这个MethodCheckType对象的一个实例,另一方面,我有一个 XML 文档,我从中序列化了这个对象。现在我想将此实例转换为字符串形式的 XML 文档。在此之后,我必须证明两个字符串(XML 文档)是否相同。我必须这样做,因为我对第一种方法进行了单元测试,在该方法中我将 XML 文档读入 aStringReader并将其序列化为一个MethodCheckType对象。
采纳答案by Tomas Grosup
Here are conversion method for both ways. this = instance of your class
这是两种方式的转换方法。this = 你的类的实例
public string ToXML()
{
using(var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
}
public static YourClass LoadFromXMLString(string xmlText)
{
using(var stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
}
回答by William Smith
I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:
我意识到这是一篇很老的帖子,但是在查看了 LB 的回复后,我想到了如何改进已接受的答案并使其适用于我自己的应用程序。这是我想出的:
public static string Serialize<T>(T dataToSerialize)
{
try
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
catch
{
throw;
}
}
public static T Deserialize<T>(string xmlText)
{
try
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch
{
throw;
}
}
These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.
这些方法现在可以放置在静态帮助器类中,这意味着每个需要序列化的类都不会重复代码。
回答by Elanchezhian Narayanasamy
public static string Serialize(object dataToSerialize)
{
if(dataToSerialize==null) return null;
using (StringWriter stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(dataToSerialize.GetType());
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
}
public static T Deserialize<T>(string xmlText)
{
if(String.IsNullOrWhiteSpace(xmlText)) return default(T);
using (StringReader stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
回答by Fred Peixoto
This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.
这是我的解决方案,对于任何列表对象,您都可以使用此代码转换为 xml 布局。KeyFather 是您的主要标签,KeySon 是您开始 Forech 的地方。
public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
{
var settings = new XmlWriterSettings
{
Indent = true
};
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement(keyFather);
foreach (var objeto in anyObject)
{
writer.WriteStartElement(keySon);
foreach (PropertyDescriptor item in props)
{
writer.WriteStartElement(item.DisplayName);
writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteFullEndElement();
writer.WriteEndDocument();
writer.Flush();
return builder.ToString();
}
}

