2008-09-16 9 views
0

XML로 직렬화하는 데 사용될 일련의 클래스에 대해 작업하고 있습니다. XML은 나에 의해 제어되지 않고 잘 구성됩니다. 안타깝게도 여러 세트의 중첩 노드가 있습니다. 그 중 일부 노드의 목적은 자식 컬렉션을 보유하는 것입니다. XML Serialization에 대한 현재 지식을 토대로,이 노드는 다른 클래스를 필요로합니다..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 가지 클래스가 가장 적합 할 것입니다. usergroup 개체가 포함 된 클래스 root입니다. 그러나, 나는 알아낼 수있는 최고의 내가 usersgroups 각각 usergroup의 컬렉션을 포함 root, users, user, groupsgroup을위한 클래스를 필요로하고, rootusersgroups 개체가 포함되어 있습니다.

저 밖에 누구보다 저보다 잘 아는 사람이 있습니까? (거짓말하지 마라, 내가 거기 있음을 안다).

답변

6

을 사용하지 않습니까? 그것은 꽤 좋았고 이런 일을 정말 쉽게 해줍니다 (나는 그것을 아주 많이 사용합니다!).

당신은 단순히 몇 가지 속성을 가진 클래스의 속성을 꾸미고 나머지는 모두

당신이 XmlSerializer를을 사용하여 생각 해 봤나 또는 특별한 이유가 왜이 ... 당신을 위해 이루어집니다?

는 Heres는 필요한 모든 작업의 ​​코드는 위의 (두 가지)를 직렬화 얻을 :

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

XMLSerializer를 사용하고 있지만, 가장 잘 알 수있는 것은 하나의 요소 이름 만 클래스 나 속성에 적용 할 수 있다는 것입니다. 나는 그들이 수행하는 모든 작업이 다른 객체의 콜렉션을 보유하는 몇 가지 중간 클래스를 가지고있다. 결과는 적절한 XML이지만 엉덩이의 고통은 나 자신을 인스턴스화합니다. –

+0

데모 코드 추가 –

+0

@Rob Cooper : 코드 펀치를 때리는 +1. – user7116

0

당신은 사용자 개체의 배열로 정의 된 사용자가 만 필요합니다. XmlSerializer가 적절하게 렌더링합니다. 내가 http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx

당 등의 XSD를 생성하려면 Visual Studio를 사용하고 당신을위한 클래스 계층을 뱉어 명령 행 유틸리티 XSD.EXE를 사용하는 것이 좋습니다 것입니다, 또한 http://www.informit.com/articles/article.aspx?p=23105&seqNum=4

:

예는이 링크를 참조하십시오

0

제가 생각하기에이 수업을 다시 작성한 것은 당신이하려는 일과 비슷합니다. XML로 직렬화하려는 객체에서이 클래스의 메서드를 사용합니다. 예를 들어, 직원이 주어진 ...

유틸리티를 사용하여; using System.Xml.직렬화;

[XmlRoot ("직원")] 공용 클래스 직원 { 개인 문자열 이름 = "스티브";

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

개체 유형 (사원) 직렬화 여야

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

}

이 코드를 출력해야한다. [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(); 
      } 
     } 
    } 
}