Imagine we have the following file, saved in c:\contacts.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<contacts> | |
<contact id="1"> | |
<firstName>Orlando</firstName> | |
<lastName>Karam</lastName> | |
</contact> | |
<contact id="2"> | |
<firstName>Lina</firstName> | |
<lastName>Colli</lastName> | |
</contact> | |
</contacts> |
Then we can access it as follows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
XDocument loaded = XDocument.Load(@"C:\contacts.xml"); | |
var contacts = from c in loaded.Descendants("contact") | |
select new { | |
id=(int)c.Attribute("id"), | |
name=(string)c.Element("firstName") +" " +(string)c.Element("lastName"), | |
}; | |
foreach (var c in contacts) | |
Console.WriteLine("Contact: id={0}, name = {1}", c.id, c.name); |
- on an XDocument, we can call descendants and pass it an element name, to get all the elements with that name (we can also call the no-args version, and get all descendants)
- What we're getting is an XElement, on which we can call methods like Element or Attribute
- We can directly cast an element into a string, and it gets us all the text inside that element
- We can cast an attribute as a string, or an int (or even a float, double or many other types)
No comments:
Post a Comment