我有一个名为 WebserviceType
的类我从 XSD 文件中的工具 xsd.exe 获得。
现在我想反序列化 WebServiceType
的一个实例对象到一个字符串。
我该怎么做?
MethodCheckType
对象的参数为 WebServiceType
数组。
我的第一次尝试就像我序列化它一样:使用 XmlSerializer
和一个 StringWriter
(在序列化时我使用了 StringReader
)。
这是我序列化 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;
编辑:
也许我可以换句话说:我有一个 MethodCheckType
的实例object 另一方面,我已经从中获得了序列化该对象的 XML 文档。现在我想将此实例转换为字符串形式的 XML 文档。在此之后,我必须证明两个字符串(XML 文档)是否相同。这是我必须做的,因为我对第一种方法进行了单元测试,在这种方法中,我将 XML 文档读入 StringReader
中。并将其序列化为 MethodCheckType
对象。
最佳答案
两种方式的转换方法如下。 this = 你类(class)的实例
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 ;
}
}
关于c# - 将对象转换为 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447529/