转换一个对象到XML字符串 [英] Convert an object to an XML string

查看:151
本文介绍了转换一个对象到XML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 WebserviceType 我从XSD文件的工具XSD.EXE了类。

I have got a class named WebserviceType I got from the tool xsd.exe from an XSD file.

现在我要反序列化 WebServiceType 对象的实例为字符串。
我怎样才能做到这一点?

Now I want to deserialize an instance of an WebServiceType object to a string. How can I do this?

MethodCheckType 对象为PARAMS一个 WebServiceType 阵列

The MethodCheckType object has as params a WebServiceType array.

我的第一个尝试是像我连载之:以的XmlSerializer 的StringWriter (而序列我用了一个 StringReader )。

My first try was like I serialized it: with a XmlSerializer and a StringWriter (while serializing I used a StringReader).

这是我在其中序列化 WebServiceType 对象的方法:

This is the method in which I serialize the WebServiceType object:

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 对象中的我有从XML文档我这个序列化对象。现在我想这种情况下转换成XML文档中的字符串形式。在此之后我得证明,如果(XML文档)两个字符串是相同的。这是我必须做的,因为我让我在其中读取XML文档转换为 StringReader 第一种方法的单元测试,并将其序列化到 MethodCheckType 对象。

Maybe I could say it in different words: I have got an instance of this MethodCheckType object 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 StringReader and serialize it into a MethodCheckType object.

推荐答案

下面是两种方式的转换方法。
本=类

Here are conversion method for both ways. this = instance of your class

public string ToXML()
    {
        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)
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(YourClass ));
        return serializer.Deserialize(stringReader) as YourClass ;
    }

这篇关于转换一个对象到XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆