programing

XML을 C #의 개체로 역 직렬화

nicescript 2021. 1. 18. 07:39
반응형

XML을 C #의 개체로 역 직렬화


그래서 다음과 같은 xml이 있습니다.

<todo-list>
  <id type="integer">#{id}</id>
  <name>#{name}</name>
  <description>#{description}</description>
  <project-id type="integer">#{project_id}</project-id>
  <milestone-id type="integer">#{milestone_id}</milestone-id>
  <position type="integer">#{position}</position>

  <!-- if user can see private lists -->
  <private type="boolean">#{private}</private>

  <!-- if the account supports time tracking -->
  <tracked type="boolean">#{tracked}</tracked>

  <!-- if todo-items are included in the response -->
  <todo-items type="array">
    <todo-item>
      ...
    </todo-item>
    <todo-item>
      ...
    </todo-item>
    ...
  </todo-items>
</todo-list>

.NET의 직렬화 라이브러리를 사용하여 이것을 C # 개체로 역 직렬화하려면 어떻게해야합니까?

현재 저는 리플렉션을 사용하고 있으며 명명 규칙을 사용하여 xml과 내 개체를 매핑합니다.


각 요소에 대한 속성과 각 하위 요소에 대한 객체의 목록 또는 배열 (만든 된 항목 사용)이있는 각 요소에 대한 클래스를 만듭니다. 그런 다음 문자열에서 System.Xml.Serialization.XmlSerializer.Deserialize를 호출하고 결과를 개체로 캐스팅합니다. System.Xml.Serialization 속성을 사용하여 요소를 ToDoList 클래스에 매핑하는 것과 같이 조정하려면 XmlElement ( "todo-list") 속성을 사용합니다.

간단한 방법은 XML을 Visual Studio로로드하고 "Infer Schema"단추를 클릭 한 다음 "xsd.exe / c schema.xsd"를 실행하여 클래스를 생성하는 것입니다. xsd.exe는 도구 폴더에 있습니다. 그런 다음 생성 된 코드를 살펴보고 적절한 경우 short를 int로 변경하는 등 조정합니다.


VS의 도구에서 xsd.exe를 사용하는 것으로 요약됩니다.

xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%"

그런 다음 리더와 디시리얼라이저로로드합니다.

public GeneratedClassFromXSD GetObjectFromXML()
{
    var settings = new XmlReaderSettings();
    var obj = new GeneratedClassFromXSD();
    var reader = XmlReader.Create(urlToService, settings);
    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));
    obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);

    reader.Close();
    return obj;
}

형식 T이 Serializable로 표시된 경우 모든 개체를 역 직렬화합니다.

function T Deserialize<T>(string serializedResults)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var stringReader = new StringReader(serializedResults))
        return (T)serializer.Deserialize(stringReader);
}

대략 XML (Private라는 속성, ToDo라는 컬렉션 속성 등)과 일치하는 어셈블리의 클래스가 있어야합니다.

The problem is that the XML has elements that are invalid for class names. So you'd have to implement IXmlSerializable in these classes to control how they are serialized to and from XML. You might be able to get away with using some of the xml serialization specific attributes as well, but that depends on your xml's schema.

That's a step above using reflection, but it might not be exactly what you're hoping for.


Checkout http://xsd2code.codeplex.com/

Xsd2Code is a CSharp or Visual Basic Business Entity class Generator from XSD schema.


There are a couple different options.

  • Visual Studio includes a command line program called xsd.exe. You use that program to create a schema document, and use the program again on the schema document to creates classes you can use with system.xml.serialization.xmlserializer
  • You might just be able to call Dataset.ReadXml() on it.

You should have a look at http://www.canerten.com/xml-c-class-generator-for-c-using-xsd-for-deserialization/

There's a (Microsoft) tool that helps creating the needed XSD to properly deserialize XML into an object


i had the same questions few years back that how abt mapping xml to C# classes or creating C# classes which are mapped to our XMLs, jst like we do in entity Framework (we map tables to C# classes). I created a framework finally, which can create C# classes out of your XML and these classes can be used to read/write your xml. Have a look

ReferenceURL : https://stackoverflow.com/questions/226599/deserializing-xml-to-objects-in-c-sharp

반응형