patterncsharpMinor
Reading XML in C#
Viewed 0 times
readingxmlstackoverflow
Problem
This seems like rather too much nesting:
This is P
I'm new to reading XML in C#. Surely there is a better way?
using (XmlReader reader = XmlReader.Create(filename))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Width":
map.Width = ParseXMLValue(reader);
break;
case "Height":
map.Height = ParseXMLValue(reader);
break;
case "TileSize":
map.TileSize = ParseXMLValue(reader);
break;
case "Layers":
map.LayerCount = ParseXMLValue(reader);
break;
case "Layout":
ParseLayout(reader);
break;
case "Layer":
currentLayerIndex = ParseLayer(reader);
break;
case "CollisionLayer":
currentLayerIndex = ParseCollisionLayer();
break;
case "Row":
ParseRow(reader);
break;
}
}
}
}This is P
arseXMLValue(reader):private int ParseXMLValue(XmlReader reader)
{
reader.Read();
return int.Parse(reader.Value);
}I'm new to reading XML in C#. Surely there is a better way?
Solution
Yes, much.
http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html
It works like:
Though I don't understand the logic in your snippet as you're setting elements of the same member repeatedly, so I'm not going to reserve giving a more eleborate use case that might match your functionality better, though I would suggest reading the msdn articles for IEnumerable.Select() and IEnumerable.Where() to get an idea how to use it for your particular purposes.
Select: http://msdn.microsoft.com/en-us/library/bb548891.aspx
Where: http://msdn.microsoft.com/en-us/library/bb534803.aspx
XDocument is the easier way. Though it does not perform as well if your documents are of significant size or performance is absolutely imperative:http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html
It works like:
XDocument someXmlDoc = XDocument.Create(fileName);
IEnumerable widthElements = someXmlDoc.Descendants("Width");
int[] widthValues = widthElements.Select(xelement => int.Parse(xelement.Value)).ToArray();Though I don't understand the logic in your snippet as you're setting elements of the same member repeatedly, so I'm not going to reserve giving a more eleborate use case that might match your functionality better, though I would suggest reading the msdn articles for IEnumerable.Select() and IEnumerable.Where() to get an idea how to use it for your particular purposes.
Select: http://msdn.microsoft.com/en-us/library/bb548891.aspx
Where: http://msdn.microsoft.com/en-us/library/bb534803.aspx
Code Snippets
XDocument someXmlDoc = XDocument.Create(fileName);
IEnumerable<XElement> widthElements = someXmlDoc.Descendants("Width");
int[] widthValues = widthElements.Select(xelement => int.Parse(xelement.Value)).ToArray();Context
StackExchange Code Review Q#4343, answer score: 5
Revisions (0)
No revisions yet.