sir_thursday
sir_thursday

Reputation: 5409

Using a XML DataReader

I was using a SqlDataReader to read data from a Scenarios table as such:

string Data = reader["ScenarioData"].ToString();

However, now my ScenarioData field is XML ntext. How can I read the XML data with the DataReader? For example, lets say I wanted to read the Url "http://google.com".

Scenario Data field:

<Scenario Name="Scenario1" Feature="Feature1">
<Steps>
<Step Url="http://google.com"></Step>
</Steps>
</Scenario>

Upvotes: 0

Views: 7987

Answers (2)

Mechanical Object
Mechanical Object

Reputation: 666

Given the fact that you have already your XML in a variable of type string, I would suggest the following :

SqlDataReader reader= cmd.ExecuteReader();
while (reader.Read())
{
    ..... 
    // you have already an xml string stocked in data
    string data = (string)reader["ScenarioData"];
    // parse it
    var doc = XDocument.Parse(data);
    var step = doc.Descendants("Step").Attributes().FirstOrDefault();
    var url = step != null ? step.Value : String.Empty;
    ......
}

There is also a way to read Xml using SqlXml, you can find more information here

Upvotes: 4

Cam Bruce
Cam Bruce

Reputation: 5689

using System.Xml.Linq;

var xml = XElement.Parse(reader["ScenarioData"].ToString());

//assuming there can be multiple <step> elements
var steps = xml.Element("Scenario").Element("Steps").Elements("Step");
var url = steps.First().Attribute("Url").Value;

Upvotes: 0

Related Questions