C#将Xml反序列化为对象并再次序列化回Xml

时间:2011-08-17 18:25:19

标签: c# xml json-framework

我想使用JsonFx将XML转换为自定义类型和LINQ查询。任何人都可以再次提供反序列化和序列化的示例吗?

以下是我正在使用的XML示例。 粘贴在此处的XML:http://pastebin.com/wURiaJM2

JsonFx支持几种将json绑定到.net对象(包括动态对象)的策略。 https://github.com/jsonfx/jsonfx

亲切的问候 硅

PS我确实尝试将xml文档粘贴到StackOverflow中,但它删除了很多文档引号和XML声明。

2 个答案:

答案 0 :(得分:1)

这是我用过的方法。可能需要一些调整:

    public static string SerializeObject<T>(T item, string rootName, Encoding encoding)
    {

        XmlWriterSettings writerSettings = new XmlWriterSettings();
        writerSettings.OmitXmlDeclaration = true;
        writerSettings.Indent = true;
        writerSettings.NewLineHandling = NewLineHandling.Entitize;
        writerSettings.IndentChars = "    ";
        writerSettings.Encoding = encoding;

        StringWriter stringWriter = new StringWriter();

        using (XmlWriter xml = XmlWriter.Create(stringWriter, writerSettings))
        {

            XmlAttributeOverrides aor = null;

            if (rootName != null)
            {
                XmlAttributes att = new XmlAttributes();
                att.XmlRoot = new XmlRootAttribute(rootName);

                aor = new XmlAttributeOverrides();
                aor.Add(typeof(T), att);
            }

            XmlSerializer xs = new XmlSerializer(typeof(T), aor);

            XmlSerializerNamespaces xNs = new XmlSerializerNamespaces();
            xNs.Add("", "");

            xs.Serialize(xml, item, xNs);
        }

        return stringWriter.ToString();
    }

对于反序列化:

    public static T DeserializeObject<T>(string xml)
    {
        using (StringReader rdr = new StringReader(xml))
        {
            return (T)new XmlSerializer(typeof(T)).Deserialize(rdr);
        }
    }

并称之为:

string xmlString =  Serialization.SerializeObject(instance, "Root", Encoding.UTF8);

ObjectType obj = Serialization.DeserializeObject<ObjectType>(xmlString);

希望这会有所帮助。 Serialize方法中的rootName参数允许您在生成的xml字符串中自定义根节点的值。此外,您的类必须使用适当的Xml属性进行修饰,这些属性将控制实体的序列化方式。

答案 1 :(得分:0)

这篇文章解释了如何从XML文件创建XSD和类,然后介绍了序列化和反序列化。 http://geekswithblogs.net/CWeeks/archive/2008/03/11/120465.aspx

将此技术与XSD.exe一起使用以创建XSD,然后在CS文件中创建类,我能够进行序列化,然后再次反序列化。

然而,序列化过程并不能创建源XML的精确表示,因此仍有一些后期工作要做。

相关问题