Reputation: 2364
How can I parse XML data into an array using C#?
<details>
<row>
<var name="Year" value=""2008"" />
<var name="person" value=""10202"" />
</row>
<row>
<var name="Year" value=""2007"" />
<var name="person" value=""11202"" />
</row>
</details>
Upvotes: 1
Views: 14316
Reputation: 112807
From the example, it looks to me like you are hoping to get this:
var rows = XDocument.Load("filename.xml")
.Root.Elements()
.Select(row => row.Elements()
.ToDictionary(v => v.Attribute("name").Value,
v => v.Attribute("value").Value);
This will create an IEnumerable<Dictionary<string, string>>
, where each entry in the IEnumerable
is a "row" and each entry in the inner dictionaries is a "variable".
If you are looking to create a more strongly-typed solution, and can guarantee the XML structure is always two variables, one named budgetYear
and one named account
, then something like this would work:
// Probably needs a better name.
struct YearAndAccount
{
private readonly int budgetYear;
private readonly string accountId;
public int BudgetYear { get { return this.budgetYear; } }
public string AccountId { get { return this.accountId; } }
public YearAndAccount(int budgetYear, string accountId)
{
this.budgetYear = budgetYear;
this.accountId = accountId;
}
}
var rows = XDocument.Load("filename.xml")
.Root.Elements()
.Select(row => new YearAndAccount(
int.Parse(row.Elements().Single(el => el.Attribute("name").Value == "budgetYear")
.Attribute("value").Value),
row.Elements().Single(el => el.Attribute("name").Value == "account")
.Attribute("value").Value));
This will create an IEnumerable<YearAndAccount>
.
The parsing code for the strongly-typed solution is so amazingly icky because your XML is very poorly structured; a better structure would be something like
<details>
<yearAndAccount>
<budgetYear>2008</budgetYear>
<account>10202</account>
</yearAndAccount>
<yearAndAccount>
<budgetYear>2007</budgetYear>
<account>11202</account>
</yearAndAccount>
</details>
in which case the code would simply be
var rows = XDocument.Load("filename.xml")
.Root.Elements()
.Select(row => new YearAndAccount(row.Element("budgetYear").Value,
int.Parse(row.Element("account").Value)));
Upvotes: 4
Reputation: 5773
Xml Serialization/Deserialization in .Net can be achieved by:
Upvotes: 2
Reputation: 498904
What you want to achieve is called deserialization - there are many ways to achieve it.
In the .NET framework, one of the newer classes with good control over how this is achieved is the DataContractSerializer
. You can see an example of how it works in the example at the bottom of the linked documentation.
Without concrete examples, this is as far as I can help.
Upvotes: 0