LINQ to XML : LINQ for XML documents






LINQ to XML 은 새로운 XML DOM 이다. 새로운  XML DOM 은 standard query operators 를 이용하고, XML document 와 XML 조각을 만들기 위한 간단한 방법을 제공해 준다.

※ LINQ to XML 에서 알아야 할 것은 다음과 같다.
1. XDocument object 안에서 XML document 를 읽는 방법
2. object 로 부터 element 들을 쿼리하는 방법
3. scratch 로 부터 document 와 element 를 생성하는 방법

Namespace
LINQ to XML 은 System.Xml.Linq 를 참조해야 한다.
using System.Xml.Linq





< 예제 >

테스트할 XML 파일

	
	
	
	
	
	
	
	





XML 파일로 부터 읽은 데이터를 저장할 클래스를 정의 한다.
namespace LINQtoXML
{
    public class Customer
    {
        public string CustomerID { get; set; }
        public string City { get; set; }

        public override string ToString()
        {
            return CustomerID + "\t" + City;
        }
    }
}




XML 파일을 읽어 출력


var results = CreateXMLCustomers();
dataGridView1.DataSource = results.ToList();


코드를 보면 알 수 있듯이 LINQ 는 Generic Collection 을 사용한다. XDocument 클래스를 사용하여 XML 파일을 읽는다. Load 메소드의 인수로 XML 파일의 경로를 주면 되는데, 디폴트로는 현재 실행 파일의 위치이다. XML 파일의 내용을 제네릭 클래스에 넣어야 하기 때문에 XML 파일에서 City 와 CustomerID 값을 사용하여 새로운 Customer 객체를 생성해서 제네릭 클래스에 넣어 주었다.







City 가 London 인 사람만 출력
var results = from c in CreateXMLCustomers()
                   where c.City == "London"
                   select c;
dataGridView1.DataSource = results.ToList();





 여기서 중요한 점은 LINQ to Object 를 사용한 예제와 비교했을 때 쿼리문은 동일하다는 것이다.



< 소스 코드 >






위의 방법은 XML 데이터를 사용자 정의 클래스를 생성하여 컬렉션으로 만든 다음에 LINQ 를 이용한 것이다. 이 방법 외에 사용자 정의 클래스를 만들지 않고 직접 XML 문서를 쿼리하고, 또한 결과를 XML 문서를 만드는 방법이 있다. 아래 소스를 참조.

/**
@brief XDocument, XElement을 이용한 XML 직접 쿼리
@note  Load 메소드는 XDocument 클래스 타입을 리턴하며, XML 데이터 내용을 그대로 갖는다.
@note  XDoment 객체를 LINQ 쿼리 결과 XElement<> 제네릭 컬렉션 객체를 얻게 된다.
           하나의 XElement 는 하나의 레코드를 표현한다.
@note  XML 을 쿼리할 때, XML 데이터를 담을 클래스를 미리 생성하여, 그 클래스를 쿼리
           할 수도 있고, 이와 같이 직접 XML 데이터를 쿼리할 수도 있다.
*/        
private void XMLQuery()
{
    var doc = XDocument.Load("Customers.xml");
    var results = from c in doc.Descendants("Customer")
                       where c.Attribute("City").Value == "London"
                       select c;

     // dataGridView 에 출력
     DataTable tblCustomers = new DataTable("tblCustomers");
     dataGridView1.DataSource = tblCustomers;

     DataColumn col = new DataColumn("CustomerID", typeof(string));
     col.MaxLength = 10;
     col.AllowDBNull = false;
     col.Unique = true;
     tblCustomers.Columns.Add(col);
     tblCustomers.PrimaryKey = new DataColumn[] { col };

     col = new DataColumn("City", typeof(string));
     col.AllowDBNull = false;
     tblCustomers.Columns.Add(col);

     DataRow row;
     foreach (var contact in results)
     {
         row = tblCustomers.NewRow();
         row["CustomerID"] = contact.Attribute("CustomerID").Value;
         row["City"] = contact.Attribute("City").Value;
         tblCustomers.Rows.Add(row);
      }

      // 쿼리 결과로 새로운 XML 파일 생성
      XElement transformedResults = 
                    new XElement("Londoners", from customer in results
                                  select new XElement("Contact",
                                               new XAttribute("ID", customer.Attribute("CustomerID").Value),
                                               new XElement("Name", customer.Attribute("ContactName").Value),
                                               new XElement("City", customer.Attribute("City").Value)));
     transformedResults.Save("Output.xml");
}


< 소스 코드 >






Posted by six605
,