如何创建一个要从 XML 反序列化的类

如何创建必须用于反序列化 XML 的 C# 类,如下所示


<?xml version="1.0" encoding="utf-8"?>

<XML>

    <StatusCode>-2</StatusCode>

    <Warnings />

    <Errors>

        <Error> Debtor #2 Invalid Postal Code</Error>

        <Error>Invalid lien term</Error>

    </Errors>

</XML>


智慧大石
浏览 144回答 3
3回答

子衿沉夜

尝试以下:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.Xml.Serialization;namespace ConsoleApplication110{&nbsp; &nbsp; class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; const string INPUT_FILENAME = @"c:\temp\test.xml";&nbsp; &nbsp; &nbsp; &nbsp; const string OUTPUT_FILENAME = @"c:\temp\test1.xml";&nbsp; &nbsp; &nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlReader reader = XmlReader.Create(INPUT_FILENAME);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlSerializer serializer = new XmlSerializer(typeof(XML));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XML xml = (XML)serializer.Deserialize(reader);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlWriterSettings settings = new XmlWriterSettings();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; settings.Indent = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME, settings);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; serializer.Serialize(writer, xml);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public class XML&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int StatusCode { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string Warnings { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [XmlArray("Errors")]&nbsp; &nbsp; &nbsp; &nbsp; [XmlArrayItem("Error")]&nbsp; &nbsp; &nbsp; &nbsp; public List<string> errors { get; set; }&nbsp; &nbsp; }}

倚天杖

你的班级应该是这样的:public class ErrorClass{&nbsp; &nbsp; struct Error&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public String message;&nbsp; &nbsp; }&nbsp; &nbsp; struct Warning&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public String message;&nbsp; &nbsp; }&nbsp; &nbsp; int StatusCode;&nbsp; &nbsp; List<Error> Errors;&nbsp; &nbsp; List<Warning> Warnings;}错误和警告结构可能包含更多您发布的示例中未使用的项目。

慕盖茨4494581

要基于 XML 创建类,请将 xml 复制到剪贴板,然后在 Visual Studio 2017 中,选择菜单选项:编辑/选择性粘贴/将 XML 粘贴为类。
打开App,查看更多内容
随时随地看视频慕课网APP