I'm reading in some XML and displaying it in a DataGridView which works great.
However, my life would be 10x easier if I could grab specific Elements and read their content. (Im using XmlReader)
Additionally, is there a simple way to loop through an element? I need to grab the count and then loop through each "Facility" but I cant seem to get this working properly. Adding another "While(read)" in wasnt a great solution.
I would prefer not to switch to another reader at this time, I'm in to deep with this one at the moment.
XML Data:
<data>
<count>2</count>
<facility>
<typeId>1</typeId>
<type>Beds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
<facility>
<typeId>2</typeId>
<type>EDBeds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
</data>
Code:
while (xr.Read())
{
if (xr.Name.Equals("count"))
{
valueName.Text = "We currently have " + xr.ReadElementContentAsString() + " facilities open.";
}
while (xr.ReadToFollowing("facility"))
{
//Add a new row for data if we are at a new Facility element
if (xr.NodeType == XmlNodeType.Element && xr.Name == "facility")
{
row = generalData.Rows.Add();
col = 0;
}
//Loop through current facility Element
}
}
See this post why you should prefer XDocument
over XmlReader
. As it states the API for XDocument is alot easier and supports 'LINQ To XML'. XmlReader is has become obsolete since it's out dated and contains bugs.
var xml = @"
<data>
<count>2</count>
<facility>
<typeId>1</typeId>
<type>Beds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
<facility>
<typeId>2</typeId>
<type>EDBeds</type>
<quantity>0</quantity>
<description>null</description>
</facility>
</data>";
var xDocument = XDocument.Load( new StringReader( xml ) );
var facilityElements = xDocument.Descendants().Where( x => x.Name == "facility" );
// Count the elements
var count = facilityElements.Count();
foreach ( var facilityElement in facilityElements )
{
// Handle elements
}
// Adds an facility element
var facility = new XElement( "facility" );
var typeId = new XElement( "typeId" );
typeId.SetValue(3);
facility.Add( typeId );
xDocument.Element( "data" ).Add( facility );