score:2
You can use Enumerable.Zip to merge parameter names sequence with parameter values sequence:
var reports = from r in xml.Root.Elements("Report")
let parameters = r.Element("ParameterList")
select new {
Name = (string)r.Attribute("Name"),
Parameters = parameters.Elements("Name")
.Zip(parameters.Elements("Value"),
(n,v) => new {
Name = (string)n,
Value = (string)v
})
};
That gives following reports collection:
[
{
"Name": "JobNotClose",
"Parameters": [
{
"Name": "@StationCode",
"Value": "LAX"
},
{
"Name": "@ShipmentType",
"Value": "SE|SI"
}
]
},
{
"Name": "JobWithoutSales",
"Parameters": [
{
"Name": "@StationCode",
"Value": "PA"
},
{
"Name": "@JobDateFrom",
"Value": "2013-10-1"
},
{
"Name": "@JobDateTo",
"Value": "2013-10-31"
}
]
}
]
score:0
Perhaps this will work.
You could take ParameterList elements as an IEnumerable using XNode.ElementsAfterSelf. Then loop through the result set and assume the elements are in pairs.
This will essentially give you a way to parse the elements in the order they appear in the ParameterList without worrying about .Descendants messing with the order.
Of course, the big assumption here is that the elements are always in pairs.
score:1
Try this (and by try I mean use):
var reports = xml.Descendants("Report").Select(reportElement => new
{
Name = reportElement.Attribute("Name").Value,
Parameters = reportElement.Descendants("ParameterList").Select(parameter =>
{
List<string> names = parameter.Elements("Name").Select(x=>x.Value).ToList();
List<string> values = parameter.Elements("Value").Select(x=>x.Value).ToList();
List<object> pairs=new List<object>();
for (int i = 0; i < names.Count; i++)
{
pairs.Add(new { Name = names[i], Value = values[i] });
}
return pairs;
}).ToList()
}).ToList();
You can remove both ToList()
calls. It just made it easier to test. Of course, there's the possibility that in your XML, the <Name> <Value>
tags are not always complete (i.e. Name
without Value
). You can check that before doing the for
loop.
EDIT: An alternative:
Dictionary<string, List<Tuple<string, string>>> rep = new Dictionary<string, List<Tuple<string, string>>>();
foreach (XElement report in xml.Elements("Report"))
{
rep.Add(report.Attribute("Name").Value, new List<Tuple<string, string>>());
List<string> names = report.Elements("ParameterList").FirstOrDefault().Elements("Name").Select(x => x.Value).ToList();
List<string> values = report.Elements("ParameterList").FirstOrDefault().Elements("Value").Select(x => x.Value).ToList();
for (int i = 0; i < names.Count; i++)
{
rep[report.Attribute("Name").Value].Add(new Tuple<string, string>(names[i], values[i]));
}
}
Source: stackoverflow.com
Related Query
- Parsing XML with pairs of elements using XDocument and LINQ
- Read XML with Elements and csv's into 2D array using XDocument in C#/XNA
- How to remove an element from an xml using Xdocument when we have multiple elements with same name but different attributes
- Linq To XML - Using XDocument and creating list of objects
- Querying xml child elements with prefixed namespace using LINQ to XML
- Group and sort elements in an XML document with LINQ in C#
- Parsing XML and cast elements to a typed collection using LINQ, C#
- Selecting all XML elements and their values dynamically using LINQ
- Select descendent nodes and elements from an XML using LINQ
- Querying XML with LINQ and using null in place of a particular xml attribute if it does not exist
- Read the XML using Linq and check if the elements exist
- Flatten xml with text and element nodes using LINQ to XML
- Parsing XML with values containing angle brackets, using Linq
- Read last n elements of an XML file with Linq XDocument
- Using linq to merge multiple XML files with the same structure and removing duplicates based on a key
- How to concatenate all child elements with same names values using LINQ to XML
- XML compare Elements and Values using LINQ to XML
- C# parsing xml document with LINQ where there are varying number of duplicate elements
- Can XML with optional elements be used with LINQ and Anonymous Types?
- Linq ebay XML Parsing ASP and C# using a query style?
- Reading XML with XDocument and LINQ Descendant Confusion
- I need to save the XML file using linq with xml code in C#
- How to query XML with the same element and attribute name using linq
- Extracting information from xml using XDOCUMENT and LINQ (C#)
- Get Attribute Values using LINQ to XML with Unknown Elements
- Filter xml using xpath and linq (price with decimal separator and thousands separator spanish) VB. NET
- C# Reading multiple elements with same name using LINQ to XML
- Construct a list of wpf Hyperlink elements from an XML source file using Linq
- How to get value of element with XDocument and Linq to XML
- Unable to parse xml string using Xdocument and Linq
More Query from same tag
- Combine two lists into one
- Finding the maximum valued and different typed items in an object list by using Linq
- LINQ to SQL Designer Bug
- expression syntax single field
- How To Find Highest Value In A Row And Return Column Header and it's value
- Linq expression to return the first overloaded method that takes 1 string parameter
- How to correct processing exceptions in linqXml?
- C# Entity Framework with linq returns null reference
- C# 6.0 null-conditional operator in if statements
- Dynamic Linq Datetime where
- How to sort C# Datatable with empty column values at the end
- C# sorting a List of Strings by a List of Doubles
- How do I return data in my MVC application based on Ids passed in using an array to a Kendo Grid?
- Use Linq to get the last order placed yesterday for each customer
- Entity Framework, why is this sql being generated?
- NullReferenceException Error when trying to iterate a IEnumerator
- LINQ to SQL omit field from results while still including it in the where clause
- vb.net access fields after line.split
- New column is added automaticlly when filling datagridview
- Use LINQ with GridView
- Linq - Join 2 tables and Select all columns VB.Net
- EF Core: Correct way to query data multiple levels deep in related one-to-many entities
- Using linq to find MIN(date) within linq query
- Create key for cache
- Translate query with operator 'IN' in Linq
- How to get the selected row index and that selected row's cell value using delete button
- LINQ error with ToList
- Issues with Dynamic Search Expressions in EF
- C# Linq where clause .Contains(string[])
- C# Removing a List from a List