.NET XML序列化

时间:2008-09-16 20:41:01

标签: .net xml serialization xml-serialization

我正在研究一组将用于序列化为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个班级最好。包含rootuser个对象集合的类group。但是,我能想到的最好的是我需要rootusersusergroupsgroup的课程,其中usersgroups仅包含usergroup的集合,root包含usersgroups对象。

那些知道比我更好的人吗? (别撒谎,我知道有)。

3 个答案:

答案 0 :(得分:6)

您没有使用XmlSerializer吗?这真非常棒,让这样的事情变得非常容易(我用了很多!)。

您可以使用某些属性简单地装饰您的类属性,其余的都是为您完成的。

您是否考虑过使用XmlSerializer,或者是否有特殊原因?

下面是完成上述序列化所需的所有工作的代码片段(两种方式):

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

答案 1 :(得分:0)

您只需要将Users定义为User对象数组。 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

为您吐出类层次结构

答案 2 :(得分:0)

我在当天写了这堂课,做我想的,和你想做的一样。您可以在希望序列化为XML的对象上使用此类的方法。例如,给一名员工......

使用Utilities; 使用System.Xml.Serialization;

[XmlRoot( “雇员”)] 公共级员工 {      private String name =“Steve”;

 [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();
            }
        }
    }
}