【问题标题】:Parsing XML from string C#从字符串 C# 解析 XML
【发布时间】:2015-10-17 08:33:24
【问题描述】:

我正在尝试使用此 XML 反序列化字符串 response.Content

<?xml version="1.0" encoding="utf-8"?><root><uri><![CDATA[http://api.bart.gov/api/stn.aspx?cmd=stns]]></uri><stations><station><name>12th St. Oakland City Center</name><abbr>12TH</abbr><gtfs_latitude>37.803664</gtfs_latitude><gtfs_longitude>-122.271604</gtfs_longitude><address>1245 Broadway</address><city>Oakland</city><county>alameda</county><state>CA</state><zipcode>94612</zipcode></station>

我正在使用这段代码来反序列化它:

var serializer = new XmlSerializer(typeof(Stations), new XmlRootAttribute("root"));
Stations result;
using (TextReader reader = new StringReader(response.Content))
{
    result = (Stations)serializer.Deserialize(reader);
}

然后我在这里声明了Stations

[XmlRoot]
public class Stations
{

    [XmlElement]
    public string name;

}

但是,我的name 为空。知道为什么吗?

【问题讨论】:

标签: c# .net xml xml-deserialization


【解决方案1】:

在使用XmlSerializer 时,你应该用你的类来模仿所有的 xml 结构。

[XmlRoot(ElementName = "root")]
public class Root
{
    [XmlArray(ElementName = "stations"), XmlArrayItem(ElementName = "station")]
    public Station[] Stations { get; set; }
}

public class Station
{
    [XmlElement(ElementName = "name")]
    public string Name { get; set; }
}

然后你可以用这种方式反序列化你的数据。

var data = ""; //your xml goes here
var serializer = new XmlSerializer(typeof(Root));
using (var reader = new StringReader(data))
{
    var root = (Root)serializer.Deserialize(reader);
}

【讨论】:

    【解决方案2】:

    Stations 不应该是一个类,它应该是Station 元素的集合。

    【讨论】:

      【解决方案3】:

      Stations 是 Station 对象的列表。 Stations 没有名为 Name 的元素,只有 Station 有。

      你可能应该做类似的事情

         public Station[] Stations
      

      在根类中。

      然后使用 Name 属性定义一个名为 Station 的新类。

      【讨论】:

      • 我还需要 Stations 课程吗?
      • 您需要一个类来保存 Stations 属性。只要它用 XmlRoot 属性装饰,我认为它应该可以工作。
      • 站 = (Station[])serializer.Deserialize(reader); ^在此行出现错误:无法将 Station 类型的对象转换为 Station[]
      • 您应该只需要反序列化根对象(让序列化程序找出其余的)。请参阅此问题中的示例:stackoverflow.com/questions/364253/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多