简体   繁体   English

将XML响应转换为C#对象-错误(不期望xmlns =''>)

[英]Converting XML response to C# object - Error ( xmlns=''> was not expected )

I've been trying out a bunch of tips and tricks specified in related topics without any success. 我一直在尝试一堆在相关主题中指定的技巧和窍门,但没有成功。

For some reason I can't deserialise my XML-string to C# class object. 由于某种原因,我无法将XML字符串反序列化为C#类对象。 I get promoted with this error: <DepartureBoard xmlns=''> was not expected. 我因以下错误而晋升: <DepartureBoard xmlns=''> was not expected.

I want to fetch the child element "Departure" as an object with it's attributes and add the objects to a list. 我想获取子元素“ Departure”作为具有其属性的对象,并将对象添加到列表中。

This is the XML-data response from the API (made it shorter): 这是来自API的XML数据响应(简化了):

<?xml version="1.0" encoding="UTF-8"?>
<DepartureBoard xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd" servertime="01:52" serverdate="2017-04-09">
    <Departure name="SJ REGIONAL" sname="TÅG" type="VAS" stopid="9022014081600002" stop="Trollhättan station, Trollhättan" time="14:07" date="2017-04-09" journeyid="9015074172200363" direction="Göteborg" track="2" rtTime="14:07" rtDate="2017-04-09" fgColor="#00A5DC" bgColor="#ffffff" stroke="Solid">
    <JourneyDetailRef ref="longUrlHere" />
    </Departure>
    <Departure name="VÄSTTÅGEN" sname="TÅG" type="VAS" stopid="9022014081600002" stop="Trollhättan station, Trollhättan" time="14:22" date="2017-04-09" journeyid="9015014172103251" direction="Göteborg" track="2" rtTime="14:22" rtDate="2017-04-09" fgColor="#00A5DC" bgColor="#ffffff" stroke="Solid">
    <JourneyDetailRef ref="longUrlHere" />
    </Departure>
</DepartureBoard>

This is the method where I try to do the conversion: 这是我尝试进行转换的方法:

public async Task<List<DepartureBoard>> GetDepartureBoard()
    {
        string url = "theApiUrlHere";
        HttpClient client = new HttpClient();
        string token = await oauth.RefreshToken();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        HttpResponseMessage response = await client.GetAsync(url);
        HttpContent content = response.Content;
        HttpContentHeaders headers = response.Content.Headers;

        byte[] mycontent = await response.Content.ReadAsByteArrayAsync();

        string xmlString = Encoding.Default.GetString(mycontent);
        StringReader reader = new StringReader(xmlString);

        List<DepartureBoard> result;

        XmlSerializer xs = new XmlSerializer(typeof(List<DepartureBoard>), new XmlRootAttribute("Departure"));

        result = (List<DepartureBoard>)xs.Deserialize(reader);

        return result;
    }

The C# class was generated using the "Paste as special". C#类是使用“特殊粘贴”生成的。

using System;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Data.SqlTypes;


/// <remarks/>
[SerializableAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
/* I've tried adding both "http://www.w3.org/2001/XMLSchema-instance"
  and "http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd" to
   the namespace attribute below without success. 
  It was left empty by default. */

[XmlRoot(Namespace = "", IsNullable = false)]
public partial class DepartureBoard
{

    private DepartureBoardDeparture[] departureField;

    private string servertimeField;

    private System.DateTime serverdateField;

    /// <remarks/>
    [XmlElementAttribute("Departure")]
    public DepartureBoardDeparture[] Departure
    {
        get
        {
            return this.departureField;
        }
        set
        {
            this.departureField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string servertime
    {
        get
        {
            return this.servertimeField;
        }
        set
        {
            this.servertimeField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute(DataType = "date")]
    public System.DateTime serverdate
    {
        get
        {
            return this.serverdateField;
        }
        set
        {
            this.serverdateField = value;
        }
    }
}

/// <remarks/>
[SerializableAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
public partial class DepartureBoardDeparture
{

    private DepartureBoardDepartureJourneyDetailRef journeyDetailRefField;

    private string nameField;

    private string snameField;

    private string typeField;

    private ulong stopidField;

    private string stopField;

    private string timeField;

    private System.DateTime dateField;

    private ulong journeyidField;

    private string directionField;

    private byte trackField;

    private string rtTimeField;

    private System.DateTime rtDateField;

    private bool rtDateFieldSpecified;

    private string fgColorField;

    private string bgColorField;

    private string strokeField;

    /// <remarks/>
    public DepartureBoardDepartureJourneyDetailRef JourneyDetailRef
    {
        get
        {
            return this.journeyDetailRefField;
        }
        set
        {
            this.journeyDetailRefField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string sname
    {
        get
        {
            return this.snameField;
        }
        set
        {
            this.snameField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public ulong stopid
    {
        get
        {
            return this.stopidField;
        }
        set
        {
            this.stopidField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string stop
    {
        get
        {
            return this.stopField;
        }
        set
        {
            this.stopField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string time
    {
        get
        {
            return this.timeField;
        }
        set
        {
            this.timeField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute(DataType = "date")]
    public System.DateTime date
    {
        get
        {
            return this.dateField;
        }
        set
        {
            this.dateField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public ulong journeyid
    {
        get
        {
            return this.journeyidField;
        }
        set
        {
            this.journeyidField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string direction
    {
        get
        {
            return this.directionField;
        }
        set
        {
            this.directionField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public byte track
    {
        get
        {
            return this.trackField;
        }
        set
        {
            this.trackField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string rtTime
    {
        get
        {
            return this.rtTimeField;
        }
        set
        {
            this.rtTimeField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute(DataType = "date")]
    public System.DateTime rtDate
    {
        get
        {
            return this.rtDateField;
        }
        set
        {
            this.rtDateField = value;
        }
    }

    /// <remarks/>
    [XmlIgnoreAttribute()]
    public bool rtDateSpecified
    {
        get
        {
            return this.rtDateFieldSpecified;
        }
        set
        {
            this.rtDateFieldSpecified = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string fgColor
    {
        get
        {
            return this.fgColorField;
        }
        set
        {
            this.fgColorField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string bgColor
    {
        get
        {
            return this.bgColorField;
        }
        set
        {
            this.bgColorField = value;
        }
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string stroke
    {
        get
        {
            return this.strokeField;
        }
        set
        {
            this.strokeField = value;
        }
    }
}

/// <remarks/>
[SerializableAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
public partial class DepartureBoardDepartureJourneyDetailRef
{

    private string refField;

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string @ref
    {
        get
        {
            return this.refField;
        }
        set
        {
            this.refField = value;
        }
    }
}

EDIT 编辑

In response to mkysoft 回应mkysoft

Thanks, I think I understand a little bit better now. 谢谢,我想我现在懂多了。 The error goes away when I change from List to just an DepartureBoard-object. 当我从列表更改为一个DepartureBoard对象时,错误消失了。 Though the object returns the Departure-array as null. 尽管该对象将Departure-array返回为null。 How can I access the array of "Departure" inside the DepartureBoard-object? 如何访问DepartureBoard对象内部的“ Departure”数组?

Best/ J 最佳/ J

Debug screenshot 调试屏幕截图

Xml files cannot start with list, it need to start with a root element. Xml文件不能以list开头,它需要以root元素开头。 In your xml file, DepartureBoard is root element and Departure is an array. 在您的xml文件中,DepartureBoard是根元素,Departure是一个数组。 You class is working properly with below code with xml file. 您的班级正在使用带有xml文件的以下代码正常工作。

 DepartureBoard result;
 XmlSerializer xs = new XmlSerializer(typeof(DepartureBoard), new XmlRootAttribute("DepartureBoard"));
 result = (DepartureBoard)xs.Deserialize(reader);

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

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