2008-09-16 40 views
0

我正在处理一组将用于序列化为XML的类。 XML不受我控制,组织得相当好。不幸的是,有几套嵌套节点,其中一些节点的目的只是为了保存他们的孩子。根据我目前对XML序列化的了解,这些节点需要另一个类。.NET XML Seralization

有没有办法让一个类序列化为一组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个类最好。类rootusergroup对象的集合。然而,最好的我可以计算的是,我需要一个类为rootusersusergroupsgroup,其中usersgroups分别包含的usergroup仅集合和root包含users,并groups对象。

有谁知道比我更好? (不要说谎,我知道有)。

回答

6

您是不是使用?这真是太好了,并且让这样的事情变得如此简单(我使用它非常多!)。

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

你有没有考虑使用XmlSerializer的或者是有一个特别的理由为什么不呢?

继承人所需要的所有工作的代码片段,以获得上述序列化(双向):

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

我使用的是XMLSerializer,但最好我可以指出,只能将一个元素名称应用于类或属性。我有几个中介类,他们所做的是持有其他对象的集合。其结果是正确的XML,但在实例化我自己的屁股时很痛苦。 – 2008-09-16 20:45:53

0

我今天写了这个课,做我认为的事情,与你正在做的事情类似。您可以在希望序列化为XML的对象上使用此类的方法。例如,给定一个员工...

using Utilities; 使用System.Xml。序列化;

[XmlRoot(“Employee”)] public class Employee { 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> 

对象类型(员工)必须是可序列。尝试[可序列化(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(); 
      } 
     } 
    } 
}