XML METHODS: Create a simple XML Tree, and query data using System.XML.Ling methods.


Fri Apr 15 2022 14:20:58 GMT+0000 (UTC)

Saved by @gamboirish #tree #document #xelement #xnode #xdocument #xml

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");
			//Get all child elements named "PhoneNumber"
			IEnumerable<XElement> empPhones = emp.Elements("PhoneNumber");
			foreach (XElement phone in empPhones)
				Console.WriteLine($" { phone.Value }");

This is from the book "Illustrated C#7", Chapter 20, Page 553.