简体   繁体   English

使用C#从XML读取特定任务

[英]Reading specific task from XML with C#

How we can read in a list the values from the target P (Price) from the following xml? 我们如何从以下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>

I know the procedure (there are other topics here for this) in C# but i have the query of the chances inside the target P and D. Play this any role or if i read from target P it will read all the prices like the above xml file 我知道C#中的过程(这里还有其他主题),但我对目标P和D内的机会有疑问。扮演任何角色,或者如果我从目标P读取,它将读取与上述价格相同的所有价格xml文件

 <D>
  <P>39.90999985</P> 
  <P>36.22999954</P> 
  <P>29.44000053</P> 
</D>
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)
        };
}

Alternatively, using XmlSerializer (Assuming the root-element is named <Data> ): 或者,使用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)
}

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

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