0

我们如何从以下 xml 中读取来自目标 P(价格)的值的列表?

<D d="2012-11-01">
  <P t="00:00:00+01:00">39.90999985</P> 
  <P t="01:00:00+01:00">36.22999954</P> 
  <P t="02:00:00+01:00">29.44000053</P> 
</D>
<D d="2012-11-02">
  <P t="00:00:00+01:00">32.33000183</P> 
  <P t="01:00:00+01:00">29.12999916</P> 
  <P t="02:00:00+01:00">30.18000031</P> 
  <P t="03:00:00+01:00">29.12999916</P> 
</D>

我知道 C# 中的程序(这里还有其他主题),但我查询目标 P 和 D 内的机会。扮演任何角色,或者如果我从目标 P 读取,它将读取所有价格,如上面xml文件

 <D>
  <P>39.90999985</P> 
  <P>36.22999954</P> 
  <P>29.44000053</P> 
</D>
4

1 回答 1

1
class Price
{
    public DateTime? Timestamp { get; set; }
    public decimal Price { get; set; }
}

public IEnumerable<Price> GetPrices(XDocument document)
{
    return
        from d in document.Root.Elements("D")
        let date = d.Attribute("d")
        from p in d.Elements("P")
        let time = p.Attribute("t")
        select new Price
        {
            Timestamp = (date == null || time == null)
                ? (DateTime?) null
                : DateTime.Parse(date.Value + " " + time.Value),
            Price = Convert.ToDecimal(p.Value)
        };
}

或者,使用XmlSerializer(假设根元素被命名<Data>):

[XmlType]
public class Data : List<Day>
{   
}

[XmlType("D")]
public class Day
{
    [XmlAttribute("d")]
    public string Date { get; set; }

    [XmlElement("P")]
    public List<Price> Prices { get; set; }
}

public class Price
{
    [XmlAttribute("t")]
    public string Time { get; set; }

    [XmlText]
    public decimal Value { get; set; }
}

public Data ParseXml(TextReader reader)
{
    var ser = new XmlSerializer(typeof(Data));
    return (Data) ser.Deserialize(reader)
}
于 2012-11-02T11:47:22.160 回答