将此 XML 反序列化为对象的最佳方法

发布于 2024-10-20 12:22:16 字数 2168 浏览 5 评论 0原文

在我见过的与我的类似的其他示例中,有一个根节点,然后是一个数组节点,然后是一堆数组项。我的问题是,我的根节点我的数组节点,所以我见过的示例似乎不适合我,而且我无法更改 XML 架构。这是 XML:

<articles>  
    <article>
      <guid>7f6da9df-1a91-4e20-8b66-07ac7548dc47</guid>
      <order>1</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Abu Dhabi's IPIC Eyes Bond Sale After Cepsa Buy</title>
      <summary>Abu Dhabi's IPIC has appointed banks for a potential sterling and euro-denominated bond issue, a document showed on Wednesday, after the firm acquired Spain's Cepsa in a $5 billion deal earlier this month...</summary>
      <readmore></readmore>
      <fileName></fileName>
      <articleDate>02/24/2011 00:00:00 AM</articleDate>
      <articleDateType></articleDateType>
    </article>

    <article>
      <guid>1c3e57a0-c471-425a-87dd-051e69ecb7c5</guid>
      <order>2</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Big Law Abuzz Over New China Security Review</title>
      <summary>China’s newly established foreign investment M&amp;A review committee has been the subject of much legal chatter in the Middle Kingdom and beyond. Earlier this month, the State Council unveiled legislative guidance on…</summary>
      <readmore></readmore>
      <fileName></fileName>
      <articleDate>02/23/2011 00:00:00 AM</articleDate>
      <articleDateType></articleDateType>
    </article>  
</articles>

这是我的类:

public class CurrentsResultsList
{
    public Article[] Articles;
}

public class Article
{
    public string Guid { get; set; }
    public int Order { get; set; }
    public string Type { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public DateTime ArticleDate { get; set; }
}

这是来自外部 API 的 XML 响应。

In other examples I've seen that are similar to mine, there is a root node, then an array node, and then a bunch of array items. My problem is, my root node is my array node, so examples I've seen don't seem to work for me, and I can't change the XML schema. Here's the XML:

<articles>  
    <article>
      <guid>7f6da9df-1a91-4e20-8b66-07ac7548dc47</guid>
      <order>1</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Abu Dhabi's IPIC Eyes Bond Sale After Cepsa Buy</title>
      <summary>Abu Dhabi's IPIC has appointed banks for a potential sterling and euro-denominated bond issue, a document showed on Wednesday, after the firm acquired Spain's Cepsa in a $5 billion deal earlier this month...</summary>
      <readmore></readmore>
      <fileName></fileName>
      <articleDate>02/24/2011 00:00:00 AM</articleDate>
      <articleDateType></articleDateType>
    </article>

    <article>
      <guid>1c3e57a0-c471-425a-87dd-051e69ecb7c5</guid>
      <order>2</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Big Law Abuzz Over New China Security Review</title>
      <summary>China’s newly established foreign investment M&A review committee has been the subject of much legal chatter in the Middle Kingdom and beyond. Earlier this month, the State Council unveiled legislative guidance on…</summary>
      <readmore></readmore>
      <fileName></fileName>
      <articleDate>02/23/2011 00:00:00 AM</articleDate>
      <articleDateType></articleDateType>
    </article>  
</articles>

Here's my class:

public class CurrentsResultsList
{
    public Article[] Articles;
}

public class Article
{
    public string Guid { get; set; }
    public int Order { get; set; }
    public string Type { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public DateTime ArticleDate { get; set; }
}

This is an XML response from an external API.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

明月松间行 2024-10-27 12:22:16
  1. 将其放入 Visual Studio 内的 xml 中

  2. 创建 xsd 架构

  3. 使用:

    “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe”“MyXsd.xsd”/t:lib /l:cs /c /namespace:my. xsd /outputdir:"C:\testtttt"  
    

现在你已经准备好了你的 C# 类。
你可以使用这个:

internal class ParseXML 
{
    public static xsdClass ToClass<xsdClass>(XElement ResponseXML)
    {
        return deserialize<xsdClass>(ResponseXML.ToString(SaveOptions.DisableFormatting));
    }

    private static result deserialize<result>(string XML)
    {
        using (TextReader textReader = new StringReader(XML))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(result));
            return (result) xmlSerializer.Deserialize(textReader);
        }
    } 
} 
  1. put it in a xml inside visual studio

  2. create the xsd schema

  3. use:

    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe" "MyXsd.xsd" /t:lib /l:cs /c  /namespace:my.xsd /outputdir:"C:\testtttt"  
    

now you have your c# class ready.
and you can use this:

internal class ParseXML 
{
    public static xsdClass ToClass<xsdClass>(XElement ResponseXML)
    {
        return deserialize<xsdClass>(ResponseXML.ToString(SaveOptions.DisableFormatting));
    }

    private static result deserialize<result>(string XML)
    {
        using (TextReader textReader = new StringReader(XML))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(result));
            return (result) xmlSerializer.Deserialize(textReader);
        }
    } 
} 
莫言歌 2024-10-27 12:22:16

您必须熟悉一些 Xml 属性,此代码有望生成您喜欢的 xml,希望它有所帮助:

using System;
using System.IO;
using System.Xml.Serialization;

namespace xmlTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var articles = new Articles();
            articles.ArticleArray = new ArticlesArticle[2]
            {
                new ArticlesArticle()
                    {
                        Guid = Guid.NewGuid(),
                        Order = 1,
                        Type = "deal_abstract",
                        Title = "Abu Dhabi...",
                        Summary = "Abu Dhabi...",
                        ArticleDate = new DateTime(2011,2,24)
                    },
                new ArticlesArticle()
                    {
                        Guid = Guid.NewGuid(),
                        Order = 2,
                        Type = "deal_abstract",
                        Title = "Abu Dhabi...",
                        Summary = "China...",
                        ArticleDate = new DateTime(2011,2,23)
                    },
            };

            var sw = new StringWriter();
            var xmlSer = new XmlSerializer(typeof (Articles));
            var noNamespaces = new XmlSerializerNamespaces();
            noNamespaces.Add("", ""); 
            xmlSer.Serialize(sw, articles,noNamespaces);
            Console.WriteLine(sw.ToString());
        }
    }

    [XmlRoot(ElementName = "articles", Namespace = "", IsNullable = false)]
    public class Articles
    {
        [XmlElement("article")]
        public ArticlesArticle[] ArticleArray { get; set; }
    }

    public class ArticlesArticle
    {
        [XmlElement("guid")]
        public Guid Guid { get; set; }
        [XmlElement("order")]
        public int Order { get; set; }
        [XmlElement("type")]
        public string Type { get; set; }
        [XmlElement("textType")]
        public string TextType { get; set; }
        [XmlElement("id")]
        public int Id { get; set; }
        [XmlElement("title")]
        public string Title { get; set; }
        [XmlElement("summary")]
        public string Summary { get; set; }
        [XmlElement("readmore")]
        public string Readmore { get; set; }
        [XmlElement("fileName")]
        public string FileName { get; set; }
        [XmlElement("articleDate")]
        public DateTime ArticleDate { get; set; }
        [XmlElement("articleDateType")]
        public string ArticleDateType { get; set; }
    }
}

You have to be trixy with some Xml-attributes, this code should hopefully produce the xml you like, hope it helps:

using System;
using System.IO;
using System.Xml.Serialization;

namespace xmlTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var articles = new Articles();
            articles.ArticleArray = new ArticlesArticle[2]
            {
                new ArticlesArticle()
                    {
                        Guid = Guid.NewGuid(),
                        Order = 1,
                        Type = "deal_abstract",
                        Title = "Abu Dhabi...",
                        Summary = "Abu Dhabi...",
                        ArticleDate = new DateTime(2011,2,24)
                    },
                new ArticlesArticle()
                    {
                        Guid = Guid.NewGuid(),
                        Order = 2,
                        Type = "deal_abstract",
                        Title = "Abu Dhabi...",
                        Summary = "China...",
                        ArticleDate = new DateTime(2011,2,23)
                    },
            };

            var sw = new StringWriter();
            var xmlSer = new XmlSerializer(typeof (Articles));
            var noNamespaces = new XmlSerializerNamespaces();
            noNamespaces.Add("", ""); 
            xmlSer.Serialize(sw, articles,noNamespaces);
            Console.WriteLine(sw.ToString());
        }
    }

    [XmlRoot(ElementName = "articles", Namespace = "", IsNullable = false)]
    public class Articles
    {
        [XmlElement("article")]
        public ArticlesArticle[] ArticleArray { get; set; }
    }

    public class ArticlesArticle
    {
        [XmlElement("guid")]
        public Guid Guid { get; set; }
        [XmlElement("order")]
        public int Order { get; set; }
        [XmlElement("type")]
        public string Type { get; set; }
        [XmlElement("textType")]
        public string TextType { get; set; }
        [XmlElement("id")]
        public int Id { get; set; }
        [XmlElement("title")]
        public string Title { get; set; }
        [XmlElement("summary")]
        public string Summary { get; set; }
        [XmlElement("readmore")]
        public string Readmore { get; set; }
        [XmlElement("fileName")]
        public string FileName { get; set; }
        [XmlElement("articleDate")]
        public DateTime ArticleDate { get; set; }
        [XmlElement("articleDateType")]
        public string ArticleDateType { get; set; }
    }
}
晒暮凉 2024-10-27 12:22:16

我能想到的最简单的方法可能是使用 xsd 工具。您给它 XML,它就会从中生成一个架构。您可能需要稍微调整架构,但它应该很接近。

从那里,您可以通过 xsd 发送回相同的架构,以从中生成类。

Probably the easiest way I can think of would be to use the xsd tool. You give it the XML and it will generate a schema from it. You might need to tweak the schema a bit, but it should be close.

From there, you can send that same schema back through xsd to generate classes from it.

以歌曲疗慰 2024-10-27 12:22:16
>xsd test.xml
Microsoft (R) Xml 架构/数据类型支持实用程序
[Microsoft (R) .NET Framework,版本 4.0.30319.1]
版权所有 (C) 微软公司。版权所有。
正在写入文件“test.xsd”。

>xsd /c 测试.xsd
Microsoft (R) Xml 架构/数据类型支持实用程序
[Microsoft (R) .NET Framework,版本 4.0.30319.1]
版权所有 (C) 微软公司。版权所有。
写入文件“test.cs”。

结果:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[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 articles {

    private articlesArticle[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("article", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public articlesArticle[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class articlesArticle {

    private string guidField;

    private string orderField;

    private string typeField;

    private string textTypeField;

    private string idField;

    private string titleField;

    private string summaryField;

    private string readmoreField;

    private string fileNameField;

    private string articleDateField;

    private string articleDateTypeField;

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

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

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

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

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

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

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

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

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

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

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string articleDateType {
        get {
            return this.articleDateTypeField;
        }
        set {
            this.articleDateTypeField = value;
        }
    }
}
>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'test.xsd'.

>xsd /c test.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'test.cs'.

Result:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[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 articles {

    private articlesArticle[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("article", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public articlesArticle[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class articlesArticle {

    private string guidField;

    private string orderField;

    private string typeField;

    private string textTypeField;

    private string idField;

    private string titleField;

    private string summaryField;

    private string readmoreField;

    private string fileNameField;

    private string articleDateField;

    private string articleDateTypeField;

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

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

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

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

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

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

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

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

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

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

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string articleDateType {
        get {
            return this.articleDateTypeField;
        }
        set {
            this.articleDateTypeField = value;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文