Is there any better way doing this?
I have to get both property values.
XML always has only these 2 properties.
My xml:
<Template name="filename.txt">
<Property name="recordSeparator">\r\n</Property>
<Property name="fieldCount">16</Property>
</Template>
Linq:
var property = from template in xml.Descendants("Template")
select new
{
recordDelim = template.Elements("Property").Where(prop => prop.Attribute("name").Value == "recordSeparator")
.Select(f => new { f.Value }),
fieldCount = template.Elements("Property").Where(prop => prop.Attribute("name").Value == "fieldCount")
.Select(f => new { f.Value })
};
“Better way” depends on what exactly are you trying to achieve – performance, simplicity, etc.?
I guess I would create a class that contains what you are trying to get with anonymous classes.
and then I would modify the LINQ to:
Note that this will cause
NullReferenceexception in case your Template tag does not contain two Property tags, each with specified attributes.Also it will throw an exception in parsing the integer from a FieldCount if it’s not a number.
Idea:
If the xml generated is your own, and you can change it’s format, why not do something like:
It’s easier to read and to parse, and it’s a little bit shorter.
In the end, I think this is how I would do it:
Having this class:
and this private method:
I could do in code: