简体   繁体   English

XML到C#的类问题

[英]XML to C# Class Question

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@whereEver.com</EmailAddress>
  </DefaultSendToAddressCollection>
</EmailConfiguration>

I want to create a corressponding c# class from this. 我想从中创建一个对应的c#类。 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. 在您说“仅使用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; }
    } 
}

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

You have two possibilities. 您有两种可能性。

Method 1. XSD tool 方法1。XSD工具


Suppose that you have your XML file in this location C:\\path\\to\\xml\\file.xml 假设您的XML文件位于此位置C:\\path\\to\\xml\\file.xml

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

And that's it! 就是这样! You have generated C# classes from xml file in C:\\path\\to\\xml\\file.cs 您已经从C:\\path\\to\\xml\\file.cs xml文件生成了C#类

Method 2 - Paste special 方法2-特殊粘贴


Required Visual Studio 2012+ 必需的Visual Studio 2012+

  1. Copy content of your XML file to clipboard 将XML文件的内容复制到剪贴板
  2. Add to your solution new, empty class file ( Shift + Alt + C ) 向您的解决方案中添加新的空类文件( Shift + Alt + C
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes 打开该文件,然后在菜单中单击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 <--> JSON Converters: Click 这里有一些在线XML <--> JSON转换器: 单击

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

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

XSD.EXE is the tool that produces classes specifically for the purpose of XML Serialization. XSD.EXE是专门为XML序列化目的生成类的工具。 If it produces partial classes, that's because they work for XML Serialization. 如果产生部分类,那是因为它们适用于XML序列化。 That's not what your problem is. 那不是你的问题。

Try using XSD.EXE and serializing / deserializing. 尝试使用XSD.EXE并进行序列化/反序列化。 If you get an exception again, then please catch it and then post the results of ex.ToString(). 如果再次遇到异常,请捕获该异常,然后发布ex.ToString()的结果。

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. 我将您的自定义集合更改为列表,并使用XmlArrayItem属性指定如何序列化每个电子邮件地址。 There are many such attributes to help you fine tune the serialization process. 有许多此类属性可帮助您微调序列化过程。

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

XML serialization requires attributes. XML序列化需要属性。 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]. 我通常这样做的方法是使用[Serializable]和[XmlRoot]标记类本身,然后使用[XmlElement],[XmlAttribute]或[NoSerialize]标记公共属性。

What specific problem are you having? 您有什么具体问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM