0

I have the following xml file to give an idea of layout,

<weather>
<current_conditions>
<condition data="Mostly Cloudy" /> 
<temp_f data="48" /> 
<temp_c data="9" /> 
<humidity data="Humidity: 71%" /> 
<icon data="/ig/images/weather/mostly_cloudy.gif" /> 
<wind_condition data="Wind: W at 17 mph" /> 
</current_conditions>
<forecast_conditions>
<day_of_week data="Sun" /> 
<low data="34" /> 
<high data="48" /> 
<icon data="/ig/images/weather/mostly_sunny.gif" /> 
<condition data="Partly Sunny" /> 
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Mon" /> 
<low data="32" /> 
<high data="45" /> 
<icon data="/ig/images/weather/sunny.gif" /> 
<condition data="Clear" /> 
</forecast_conditions>

I am learning c# and want to export to csv using a row for each day of the week, where info for a day is not available i need to show no data in the csv row. I appreciate the simplest solution as i am learning :)

3
  • I can get the data into a string.. Commented Jan 24, 2012 at 21:27
  • string day = "Tue"; string path = "weather/forecast_conditions[day_of_week/@data='" + day + "']/condition"; string towrite = doc.XPathSelectElement(path).Attribute("data").Value; Commented Jan 24, 2012 at 21:27
  • I'd recommend editing your post and putting what you've tried into your question! The more code, the better! Commented Jan 24, 2012 at 21:36

1 Answer 1

1

I'm assuming you want to ignore the current conditions node as it doesn't make much sense to me to have a csv file where the columns don't all match the same data. For getting all the forecast info into a csv you can use:

XDocument doc = XDocument.Parse(...);    
StringBuilder sb = new StringBuilder(1000);
foreach (XElement node in doc.Descendants("forecast_conditions"))
{
    foreach(XElement innerNode in node.Elements())
    {
       sb.AppendFormat("{0},", innerNode.Attribute("data").Value);
    }
    //Remove trailing comma
    sb.Remove(sb.Length - 1, 1);
    sb.AppendLine();
}
File.WriteAllText(@"c:\temp.csv", sb.ToString());
Sign up to request clarification or add additional context in comments.

6 Comments

this is works thanks, how could i exclude an element for example icon data ?
Also I don't understand what the "1000" does after stringbuilder? thanks
Use an if statement on the innerNode object, one of the properties will contain the name of the node. The properties name is most likely Name though I'm not 100% sure.
The 1000 just sets the default capacity of the StringBuilder. It's not important and can be left out, but check dotnetperls.com/stringbuilder-capacity if you wish to know more
Sorry, i don't see how I can use an if statement to exclude a element?
|

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.