This is my first experience with LINQ to XML, so bear with me. I’m parsing a Web Services generated XML file for values to insert into SQL Server. The XML data looks like:
...
<row>
<value>912EOE01L0K0</value>
<value>4369 </value>
<value>PTO </value>
<value>PTO03 </value>
<value>3 Days PTO </value>
<value>1</value>
<value>0</value>
<value>0</value>
<value>1</value>
<value>0</value>
<value>0</value>
<value>7.36</value>
<value>0</value>
<value>0</value>
</row>
<row>
<value>912EOE01L0K0</value>
<value>4369 </value>
<value>SICK </value>
<value>SCK07 </value>
<value>7 Sick Days </value>
<value>2.34</value>
<value>0</value>
<value>0</value>
<value>2.34</value>
<value>0</value>
<value>0</value>
<value>35.979999</value>
<value>0</value>
<value>0</value>
</row>
...
The C# class that is doing the parsing needs to be dynamic to handle a variable number of rows and values within each row, though I do know how many values will be in each row once I start parsing. I want to group (pivot?) all of the values in a row into a single object, String and comma separated if possible. I know I could do this by pulling all of the values into a list, then iterating through them and grouping every X into a “row” object, where X is the number of values in each row but it feels like there should be a more LINQ-y way to do this. Is there a LINQ query that will for each row, group all of the values into a single object?
Thanks.
This is a great application for Linq-to-Xml. Once you’ve got the XML loaded into an XDocument, you can write this:
This will give you an array of each row with the values represented as a CSV string.