0

How we can read in a list the values from the target P (Price) from the following xml?

<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

 <D>
  <P>39.90999985</P> 
  <P>36.22999954</P> 
  <P>29.44000053</P> 
</D>
3
  • 2
    You may want to consider re-wording your question, I struggle to make sense of it. Commented Nov 2, 2012 at 11:35
  • I would say that you should re-structure the xml content if you have access or are responsible for the output. Date should an element, time should be the child and price a child node of time. Commented Nov 2, 2012 at 11:37
  • Yeah sorry! If you read just the target "P" from the first and the second xml file give the same result. So it does not play any role here the chanche of t in the target "P". Done/ Commented Nov 2, 2012 at 11:39

1 Answer 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)
        };
}

Alternatively, using XmlSerializer (Assuming the root-element is named <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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.