Reputation: 95
I'm learning about reading and retrieving data from XML files. I have xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="IK.xsl"?>
<IK>
<Folders>
<Folder>
<name>nameA</name>
<info>nazwa pierwsza</info>
<komps>
<K1 id="1">komp1</K1>
<K1 id="2">komp2</K1>
<K1 id="3">komp3</K1>
<K1 id="4">komp4</K1>
<K1 id="5">komp5</K1>
</komps
</Folder>
<Folder>
<name>nameB</name>
<info>nazwa druga</info>
<komps>
<K1 id="1">komp1</K1>
<K1 id="2">komp2</K1>
<K1 id="3">komp3</K1>
<K1 id="4">komp4</K1>
<K1 id="5">komp5</K1>
</komps
</Folder>
<Folder>
<name>nameC</name>
<info>nazwa trzecia</info>
<komps>
<K1 id="1">komp1</K1>
<K1 id="2">komp2</K1>
<K1 id="3">komp3</K1>
<K1 id="4">komp4</K1>
<K1 id="5">komp5</K1>
</komps
</Folder>
</Folders>
</IK>
and class
public class Foldery
{
public Folder folder { get; set; }
}
public class Folder
{
public string name { get; set; }
public string info { get; set; }
public Komps[] komps { get; set; }
}
public class Komps
{
public string K1 { get; set; }
}
}
I want to put all Folders values into a list Folder objects using linq to xml? All the example which i found is for first level nodes and I don't know how to get to deeper level of xml and retrieve data from.
What about "komps" values which are another list of strings??
Upvotes: 2
Views: 67
Reputation: 95
I manage to get to data in komps using loops and
var komps = item.Descendants("Folder").Descendants("komps").Descendants("K1");
Upvotes: 1
Reputation: 22789
The XDocument
class has a method called Descendants. It has an overload where you can provide an XName
as a filter criteria for elements. Fortunately there is an implicit cast operator between string
and XName
.
So, in order to retrieve the Folder
elements into a List you can use the following code:
//Retrieve and load the xml
using var fs = File.OpenRead("Sample.xml");
var reader = new StreamReader(fs);
var rawXml = reader.ReadToEnd();
//Parse the xml
var document = XDocument.Parse(rawXml);
var folders = document.Descendants("Folder")
.Select(element => new Folder
{
Name = element.Element("name")?.Value,
Info = element.Element("info")?.Value,
}).ToList();
UPDATE: Providing an alternative
You can also filter for the Folders
element and ask for its child nodes:
document.Descendants("Folders").Elements()
Upvotes: 3