Лучший способ десериализации этого XML в объект - PullRequest
5 голосов
/ 04 марта 2011

В других примерах, которые я видел, которые похожи на мои, есть корневой узел, затем узел массива, а затем набор элементов массива.Моя проблема в том, что мой корневой узел - это мой узел массива, поэтому примеры, которые я видел, мне не подходят, и я не могу изменить схему 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; }
}

Это ответ XML от внешнего API.

Ответы [ 4 ]

8 голосов
/ 04 марта 2011
  1. положить его в XML внутри Visual Studio
  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);
        }
    } 
} 
5 голосов
/ 05 марта 2011

Вы должны быть триокси с некоторыми 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; }
    }
}
3 голосов
/ 04 марта 2011

Наверное, самый простой способ, которым я могу придумать, - это использовать инструмент xsd .Вы даете ему XML, и он будет генерировать из него схему.Возможно, вам придется немного настроить схему, но она должна быть закрыта.

Оттуда вы можете отправить эту же схему обратно через xsd для генерации классов из нее.

2 голосов
/ 04 марта 2011
>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'.

Результат:

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