如何在不使用xml命名空间的情况下使用C#类反序列化xml文件 [英] how to deserialize xml file using C# classes without using xml namespace

查看:156
本文介绍了如何在不使用xml命名空间的情况下使用C#类反序列化xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C#类反序列化以下XML文件。但我不想使用XMLReader或同样的东西。我需要知道如何通过使用C#类及其属性来完成它



How can I deserialize following XML file using C# classes. But I don''t want to use XMLReader or same thing. I need to know how it can be done by using C# classes and its properties

<Visibilities>
    <Visibilities AppName="Test2">
      <Visibility DisplayName="Full Name" ListOrder="2">
        <FullName>
          <FirstName PropertyName="FullName.FirstName" DisplayName="First Name"></FirstName>
          <MiddleName PropertyName="FullName.MiddleName" DisplayName="Middle Name"></MiddleName>
          <LastName PropertyName="FullName.LastName" DisplayName="Last Name"></LastName>
        </FullName>
      </Visibility>
    </Visibilities>
  </Visibilities>







我想使用以下功能






I want to use following function

public static T LoadXml<T>(string fileName) where T : new()
       {
           StreamReader reader = null;
           try
           {
               // Deserialize
               XmlSerializer ser = new XmlSerializer(typeof(T));
               reader = new StreamReader(fileName);
               T t = (T)ser.Deserialize(reader);
               if (t == null) throw new NullReferenceException("Invalid xml format");
               return t;
           }
           catch (Exception ex)
           {
               //TODO: Error
           }
           finally
           {
               if (reader != null) reader.Close();
           }

           return new T();
       }





先谢谢。



Thanks in Advance.

推荐答案

您真正需要的是数据合同: http://msdn.microsoft.com/en-us /library/ms733127.aspx [ ^ ]。



请参阅我过去提倡这种方法的答案:

如何在表单应用程序中使用XML文件编写器和阅读器? [ ^ ],

创建属性文件... [ ^ ]。



这比这要好得多解决方案1中引用的解决方案。区别在于性能。 Data Contract序列化程序每种类型只执行一次反射。它使用 System.Reflection.Emit 即时创建序列化程序集。如果您想自己开发类似的解决方案,那么您将面临非常了解CIL的需求,并且Emit代码很难调试。



-SA
What you really need is Data Contract: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

Please see my past answers advocating this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^].

This is much better then the solution referenced in Solution 1. The difference is performance. Data Contract serializer does the reflection only once per type. It creates a serialization assembly on the fly, using System.Reflection.Emit. If you wanted to develop similar solution by yourself, you would face with the need to know CIL very well, and Emit code is quite difficult to debug.

—SA


找到一个比上面提供的好的



使用C#2.0中的通用类型将对象序列化和反序列化为XML [ ^ ]
Found a good one than offered above

Serialize and Deserialize Objects as XML using Generic Types in C# 2.0[^]


这篇关于如何在不使用xml命名空间的情况下使用C#类反序列化xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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