문제

저는 XML로 직렬화하는 데 사용할 클래스 세트를 작업 중입니다.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개 클래스가 가장 좋습니다.A클래스 root 컬렉션으로 user 그리고 group 사물.하지만 내가 생각할 수 있는 가장 좋은 점은 다음을 위한 수업이 필요하다는 것입니다. root, users, user, groups 그리고 group, 어디 users 그리고 groups 다음의 컬렉션만 포함합니다. user 그리고 group 각각 그리고 root 포함 users, 그리고 groups 물체.

저 말고도 잘 아시는 분 계시나요?(거짓말하지 마세요. 그런 게 있다는 걸 압니다.)

도움이 되었습니까?

해결책

사용하지 않으시나요? XmlSerializer?그것은 정말 훌륭하고 이와 같은 일을 정말 쉽게 만들어 줍니다(나는 그것을 꽤 많이 사용합니다!).

일부 속성으로 클래스 속성을 간단히 장식하면 나머지는 모두 완료됩니다.

XmlSerializer 사용을 고려해 보셨나요? 아니면 사용하지 않는 특별한 이유가 있나요?

다음은 위의 내용을 직렬화하는 데 필요한 모든 작업의 ​​코드 조각입니다(두 가지 방법 모두).

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

다른 팁

사용자를 사용자 개체의 배열로 정의하기만 하면 됩니다.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

나는 내 생각에 당신이 하려는 것과 비슷하다고 생각하는 것을 하기 위해 이 수업을 썼습니다.XML로 직렬화하려는 개체에 이 클래스의 메서드를 사용합니다.예를 들어 직원이 있다고 가정하면...

유틸리티 사용;System.Xml.Serialization 사용;

xmlroot ( "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>

객체 유형(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();
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top