using System.Xml.Linq;
public class Example
{
public static void Main()
{
Console.Write("Linq to XML 예제 \n");
var filename = "Order.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var OrderFilepath = Path.Combine(currentDirectory, filename);
XElement Order = XElement.Load(OrderFilepath);
// Linq 형식
IEnumerable<string> partNos = from item in Order.Descendants("Item")
select (string)item.Attribute("PartNumber");
// C# 메서드 구문형식
//IEnumerable<string> partNos = Order.Descendants("Item").Select(x => (string)x.Attribute("PartNumber"));
foreach (var item in partNos)
{
Console.WriteLine(item);
}
}
}
<?xml version="1.0"?>
<Order OrderNumber="99503" OrderDate="2022-08-17">
<Address Type="Shipping">
<Name>CodeKiller</Name>
<Street>street 11</Street>
<City>killer city</City>
<State>AA</State>
<Zip>1111</Zip>
<Country>Ko</Country>
</Address>
<Address Type="Billing">
<Name>Dumper</Name>
<Street>street 100</Street>
<City>dump city</City>
<State>BB</State>
<Zip>2222</Zip>
<Country>Ko</Country>
</Address>
<Items>
<Item PartNumber="11-AA">
<ProductName>keyboard</ProductName>
<Quantity>1</Quantity>
<USPrice>100</USPrice>
<Comment>test code</Comment>
</Item>
<Item PartNumber="22-AA">
<ProductName>computer</ProductName>
<Quantity>1</Quantity>
<USPrice>1000</USPrice>
<ShipDate>2022-08-17</ShipDate>
</Item>
</Items>
</Order>