XML 到 C# 类问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1133015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:00:11  来源:igfitidea点击:

XML to C# Class Question

c#xmlclass

提问by JL.

Can someone please help me, I have this xml snippet

有人可以帮我吗,我有这个 xml 片段

<?xml version="1.0" encoding="utf-8" ?>
<EmailConfiguration>
  <DataBoxID>123</DataBoxID>
  <DefaultSendToAddressCollection>
     <EmailAddress>[email protected]</EmailAddress>
  </DefaultSendToAddressCollection>
</EmailConfiguration>

I want to create a corressponding c# class from this. Before you say - "Just use xsd.exe", the output from Xsd cannot be serialized and deserialized correct, because it generates the class using partial classes.

我想从中创建一个相应的 c# 类。在您说“只使用 xsd.exe”之前,Xsd 的输出无法正确序列化和反序列化,因为它使用部分类生成类。

Please can you tell me how to create this class.... here is the approach I took, but it doesn't work.

请你告诉我如何创建这个类......这是我采用的方法,但它不起作用。

public class EmailConfiguration
{
    private string dataBoxID;

    public string DataBoxID
    {
        get { return dataBoxID; }
        set { dataBoxID = value; }
    }

    private DefaultSendToAddressCollectionClass defaultSendToAddressCollection;

    public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection
    {
        get { return defaultSendToAddressCollection; }
        set { defaultSendToAddressCollection = value; }
    }
}

And here is the class declaration for the subclass

这是子类的类声明

public class DefaultSendToAddressCollectionClass
{
    private string[] emailAddress;
    public string[] EmailAddress
    {
        get { return emailAddress; }
        set { emailAddress = value; }
    } 
}

采纳答案by Matthew Whited

Bare minimum working... looks like you are only required to add one attribute.

最低限度的工作......看起来你只需要添加一个属性。

public class EmailConfiguration
{
    public string DataBoxID { get; set; }
    public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get; set; }
}

public class DefaultSendToAddressCollectionClass
{
    [XmlElement]
    public string[] EmailAddress { get; set; }
}

回答by Steven Sudit

XML serialization requires attributes. The way I've usually done it is to flag the class itself with [Serializable] and [XmlRoot], then mark up public properties with either [XmlElement], [XmlAttribute] or [NoSerialize].

XML 序列化需要属性。我通常这样做的方法是用 [Serializable] 和 [XmlRoot] 标记类本身,然后用 [XmlElement]、[XmlAttribute] 或 [NoSerialize] 标记公共属性。

What specific problem are you having?

你有什么具体问题?

回答by Shane Castle

Did you use VS2008's XSD?

你用过VS2008的XSD吗?

Here's the output I got:

这是我得到的输出:

c:>xsd email.xml
Writing file 'c:\email.xsd'

c:>xsd email.xsd /c /edb
Writing file 'c:\email.cs'

Generates serializable output:

生成可序列化的输出:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class EmailConfiguration : object,  System.ComponentModel.INotifyPropertyChanged {

private string dataBoxIDField;

private EmailConfigurationDefaultSendToAddressCollection[] defaultSendToAddressCollectionField;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string DataBoxID {
    get {
        return this.dataBoxIDField;
    }
    set {
        this.dataBoxIDField = value;
        this.RaisePropertyChanged("DataBoxID");
    }
}

回答by John Saunders

XSD.EXE is the tool that produces classes specifically for the purpose of XML Serialization. If it produces partial classes, that's because they work for XML Serialization. That's not what your problem is.

XSD.EXE 是专门为 XML 序列化目的生成类的工具。如果它生成部分类,那是因为它们适用于 XML 序列化。那不是你的问题。

Try using XSD.EXE and serializing / deserializing. If you get an exception again, then please catch it and then post the results of ex.ToString().

尝试使用 XSD.EXE 和序列化/反序列化。如果再次出现异常,请捕获它,然后发布 ex.ToString() 的结果。

回答by Zanoni

Using .NET 3.5:

使用 .NET 3.5:

[XmlRoot]
public class EmailConfiguration
{
    [XmlElement]
    public string DataBoxID { get; set; }

    [XmlElement]
    public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get; set; }
}

public class DefaultSendToAddressCollectionClass
{
    [XmlElement]
    public string[] EmailAddress { get; set; }
}

回答by Chris Dunaway

This class will serialize the way you want. I changed your custom collection to a List and used the XmlArrayItem attribute to specify how each email address would be serialized. There are many such attributes to help you fine tune the serialization process.

这个类将按照你想要的方式序列化。我将您的自定义集合更改为 List,并使用 XmlArrayItem 属性指定每个电子邮件地址的序列化方式。有许多这样的属性可以帮助您微调序列化过程。

[Serializable]
public class EmailConfiguration {
    private string dataBoxID;
    public string DataBoxID {
        get { return dataBoxID; }
        set { dataBoxID = value; }
    }

    private List<string> defaultSendToAddressCollection;

    [XmlArrayItem("EmailAddress")]
    public List<string> DefaultSendToAddressCollection {
        get { return defaultSendToAddressCollection; }
        set { defaultSendToAddressCollection = value; }
    }

    public EmailConfiguration() {
        DefaultSendToAddressCollection = new List<string>();
    }
}

回答by Damian Drygiel

You have two possibilities.

你有两种可能性。

Method 1. XSDtool

方法一、XSD工具



假设您的 XML 文件位于此位置 C:\path\to\xml\file.xmlC:\path\to\xml\file.xml

  1. Open Developer Command Prompt
    You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio ToolsOr if you have Windows 8 can just start typing Developer Command Promptin Start screen
  2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  3. Create XSD filefrom your xml file by typing xsd file.xml
  4. Create C# classesby typing xsd /c file.xsd
  1. 打开开发人员命令提示符
    您可以在Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools或者如果您有 Windows 8 可以在开始屏幕中开始键入开发人员命令提示符
  2. 通过键入将位置更改为您的 XML 文件目录 cd /D "C:\path\to\xml"
  3. 通过键入从您的 xml 文件创建XSD 文件xsd file.xml
  4. 通过键入创建C# 类xsd /c file.xsd

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

就是这样!您已经从 xml 文件中生成了 C# 类C:\path\to\xml\file.cs

Method 2 - Paste special

方法 2 - 特殊粘贴



所需的 Visual Studio 2012+

  1. Copy content of your XML file to clipboard
  2. Add to your solution new, empty class file (Shift+Alt+C)
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
    enter image description here
  1. 将 XML 文件的内容复制到剪贴板
  2. 添加到您的解决方案新的,空的类文件(Shift+ Alt+ C
  3. 打开该文件并在菜单中单击 Edit > Paste special > Paste XML As Classes
    在此处输入图片说明

And that's it!

就是这样!

Usage

用法



Usage is very simple with this helper class:

这个助手类的用法非常简单:

using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;

namespace Helpers
{
    internal static class ParseHelpers
    {
        private static JavaScriptSerializer json;
        private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }

        public static Stream ToStream(this string @this)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(@this);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }


        public static T ParseXML<T>(this string @this) where T : class
        {
            var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }

        public static T ParseJSON<T>(this string @this) where T : class
        {
            return JSON.Deserialize<T>(@this.Trim());
        }
    }
}

All you have to do now, is:

你现在要做的就是:

    public class JSONRoot
    {
        public catalog catalog { get; set; }
    }
    // ...

    string xml = File.ReadAllText(@"D:\file.xml");
    var catalog1 = xml.ParseXML<catalog>();

    string json = File.ReadAllText(@"D:\file.json");
    var catalog2 = json.ParseJSON<JSONRoot>();

Here you have some Online XML <--> JSONConverters: Click

这里有一些在线XML <--> JSON转换器:点击