【问题标题】:.NET XML Seralization.NET XML 序列化
【发布时间】:2010-09-09 18:14:12
【问题描述】:

我正在研究一组用于序列化为 XML 的类。 XML 不是由我控制的,而且组织得很好。不幸的是,有几组嵌套节点,其中一些的目的只是为了保存它们的子节点的集合。根据我目前对 XML 序列化的了解,这些节点需要另一个类。

有没有办法让一个类序列化为一组 XML 节点,而不仅仅是一个。因为我觉得我像泥一样清楚,所以说我们有xml:

<root>
    <users>
        <user id="">
            <firstname />
            <lastname />
            ...
        </user>
        <user id="">
            <firstname />
            <lastname />
            ...
        </user>
    </users>
    <groups>
        <group id="" groupname="">
            <userid />
            <userid />
        </group>
        <group id="" groupname="">
            <userid />
            <userid />
        </group>
    </groups>
</root>

理想情况下,最好是 3 个班级。一个类root,包含usergroup 对象的集合。但是,我能想到的最好的办法是我需要一个针对 rootusersusergroupsgroup 的类,其中 usersgroups 仅包含 user 和 @ 的集合分别为 987654333@ 和 root 包含一个 usersgroups 对象。

有谁比我更了解? (别说谎,我知道有)。

【问题讨论】:

    标签: .net xml serialization xml-serialization


    【解决方案1】:

    您没有使用XmlSerializer 吗?它非常棒,让做这样的事情变得非常容易(我经常使用它!)。

    你可以简单地用一些属性来装饰你的类属性,其余的都为你完成..

    您是否考虑过使用 XmlSerializer 或者有什么特别的原因不这样做?

    这里是序列化上述所有工作所需的代码 sn-p(两种方式):

    [XmlArray("users"),
    XmlArrayItem("user")]
    public List<User> Users
    {
        get { return _users; }
    }
    

    【讨论】:

    • 我正在使用 XMLSerializer,但我能想到的最好的办法是,您只能将单个元素名称应用于类或属性。我有几个中间类,它们所做的只是保存其他对象的集合。结果是正确的 XML,但实例化自己却很痛苦。
    • 哈哈!谢谢大家 :) 乐于助人!如果您再次遇到序列化问题,请务必询问,我最近玩得很开心(如果您这么称呼它)(请参阅我的一些 Q 的简介):) 编码快乐!
    【解决方案2】:

    您只需要将用户定义为用户对象的数组。 XmlSerializer 会为您适当地呈现它。

    有关示例,请参见此链接: http://www.informit.com/articles/article.aspx?p=23105&seqNum=4

    此外,我建议使用 Visual Studio 生成 XSD 并使用命令行实用程序 XSD.EXE 为您吐出类层次结构,根据 http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx

    【讨论】:

      【解决方案3】:

      我以前写这门课是为了做我认为的事情,类似于你想做的事情。您可以对希望序列化为 XML 的对象使用此类的方法。例如,给定一个员工...

      使用实用程序; 使用 System.Xml.Serialization;

      [XmlRoot("雇员")] 公共类员工 { 私有字符串名称 = “史蒂夫”;

       [XmlElement("Name")]
       public string Name { get { return name; } set{ name = value; } }
      
       public static void Main(String[] args)
       {
            Employee e = new Employee();
            XmlObjectSerializer.Save("c:\steve.xml", e);
       }
      

      }

      这段代码应该输出:

      <Employee>
        <Name>Steve</Name>
      </Employee>
      

      对象类型(Employee)必须是可序列化的。尝试 [Serializable(true)]。 我在某个地方有此代码的更好版本,我在编写它时只是在学习。 不管怎样,看看下面的代码。我在某个项目中使用它,所以它肯定有效。

      using System;
      using System.IO;
      using System.Xml.Serialization;
      
      namespace Utilities
      {
          /// <summary>
          /// Opens and Saves objects to Xml
          /// </summary>
          /// <projectIndependent>True</projectIndependent>
          public static class XmlObjectSerializer
          {
              /// <summary>
              /// Serializes and saves data contained in obj to an XML file located at filePath <para></para>        
              /// </summary>
              /// <param name="filePath">The file path to save to</param>
              /// <param name="obj">The object to save</param>
              /// <exception cref="System.IO.IOException">Thrown if an error occurs while saving the object. See inner exception for details</exception>
              public static void Save(String filePath, Object obj)
              {
                  // allows access to the file
                  StreamWriter oWriter =  null;
      
                  try
                  {
                      // Open a stream to the file path
                       oWriter = new StreamWriter(filePath);
      
                      // Create a serializer for the object's type
                      XmlSerializer oSerializer = new XmlSerializer(obj.GetType());
      
                      // Serialize the object and write to the file
                      oSerializer.Serialize(oWriter.BaseStream, obj);
                  }
                  catch (Exception ex)
                  {
                      // throw any errors as IO exceptions
                      throw new IOException("An error occurred while saving the object", ex);
                  }
                  finally
                  {
                      // if a stream is open
                      if (oWriter != null)
                      {
                          // close it
                          oWriter.Close();
                      }
                  }
              }
      
              /// <summary>
              /// Deserializes saved object data of type T in an XML file
              /// located at filePath        
              /// </summary>
              /// <typeparam name="T">Type of object to deserialize</typeparam>
              /// <param name="filePath">The path to open the object from</param>
              /// <returns>An object representing the file or the default value for type T</returns>
              /// <exception cref="System.IO.IOException">Thrown if the file could not be opened. See inner exception for details</exception>
              public static T Open<T>(String filePath)
              {
                  // gets access to the file
                  StreamReader oReader = null;
      
                  // the deserialized data
                  Object data;
      
                  try
                  {
                      // Open a stream to the file
                      oReader = new StreamReader(filePath);
      
                      // Create a deserializer for the object's type
                      XmlSerializer oDeserializer = new XmlSerializer(typeof(T));
      
                      // Deserialize the data and store it
                      data = oDeserializer.Deserialize(oReader.BaseStream);
      
                      //
                      // Return the deserialized object
                      // don't cast it if it's null
                      // will be null if open failed
                      //
                      if (data != null)
                      {
                          return (T)data;
                      }
                      else
                      {
                          return default(T);
                      }
                  }
                  catch (Exception ex)
                  {
                      // throw error
                      throw new IOException("An error occurred while opening the file", ex);
                  }
                  finally
                  {
                      // Close the stream
                      oReader.Close();
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-11
        • 2010-12-15
        相关资源
        最近更新 更多