2008-09-16 41 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(); 
      } 
     } 
    } 
}