using System;
using System.Collections.Generic;
using System.Xml.Linq;
class Program {
static void Main( ) {
XDocument employeeDoc = new XDocument(
new XElement("Employees",
new XElement("Employee",
new XElement("Name", "Bob Smith"),
new XElement("PhoneNumber", "408-555-1000")),
new XElement("Employee",
new XElement("Name", "Sally Jones"),
new XElement("PhoneNumber", "415-555-2000"),
new XElement("PhoneNumber", "415-555-2001")
)
)
);//Get first child XElement named "Employees"
XElement root = employeeDoc.Element("Employees");
IEnumerable<XElement> employees = root.Elements();
foreach (XElement emp in employees){
//Get first child XElement named "Name"
XElement empNameNode = emp.Element("Name");
Console.WriteLine(empNameNode.Value);
//Get all child elements named "PhoneNumber"
IEnumerable<XElement> empPhones = emp.Elements("PhoneNumber");
foreach (XElement phone in empPhones)
Console.WriteLine($" { phone.Value }");
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter