c#对象的XML字符串未返回数据

时间:2018-08-27 22:44:56

标签: c# json xml deserialization

我有一个XML字符串,我需要从该字符串中获取数据,但似乎无法返回任何行。 字符串是:

"<Tables><Table SourceQuery=\"Transaction\"><Rows><Row><ShiftID></ShiftID><EmployeeID>ANDREW</EmployeeID></Row><Row><ShiftID></ShiftID><EmployeeID>ANDREW</EmployeeID></Row></Rows></Table><Tables>"

我的代码是:

var xmlText =
            "<Tables><Table SourceQuery=\"Transaction\"><Rows><Row><ShiftID></ShiftID><EmployeeID>ANDREW</EmployeeID><StartDateTime>02/11/2018 10:30:00</StartDateTime><EndDateTime>02/11/2018 19:00:00</EndDateTime><ShiftCost></ShiftCost><Break>30</Break><Location>Main Bar</Location><Type></Type></Row></Rows></Table></Tables>";

var stringReader = new StringReader(xmlText);
var serializer = new XmlSerializer(typeof(Tables));
var neededObject =  serializer.Deserialize(stringReader) as Tables;
var rows = neededObject.Table.Rows.Row;

two muppets 行返回0行

我敢肯定,有一种更好的方法可以获取此数据,即我目前正在做的事情(尤其是它无法正常工作),但是任何建议都将不胜感激。我认为我的课程结构有问题。

将来,我将需要能够从“表”中获取sourceQuery,因此不能仅删除那些

1 个答案:

答案 0 :(得分:3)

尝试将属性添加到您的类和属性中。

[XmlRoot(ElementName = "Row")]
public class Row
{
    [XmlElement(ElementName = "ShiftID")]
    public string ShiftID { get; set; }
    [XmlElement(ElementName = "EmployeeID")]
    public string EmployeeID { get; set; }
}

[XmlRoot(ElementName = "Rows")]
public class Rows
{
    [XmlElement(ElementName = "Row")]
    public List<Row> Row { get; set; }
}

[XmlRoot(ElementName = "Table")]
public class Table
{
    [XmlElement(ElementName = "Rows")]
    public Rows Rows { get; set; }
    [XmlAttribute(AttributeName = "SourceQuery")]
    public string SourceQuery { get; set; }
}

[XmlRoot(ElementName = "Tables")]
public class Tables
{
    [XmlElement(ElementName = "Table")]
    public Table Table { get; set; }
}

c# online