본격적인 LINQ 실행을 함 해보자.
예고와는 다르게 일단 XML부터 Linq를 통해 한번 제대로 굴려보도록 하자.
1. XML 파싱하기.
먼저 다음과 같이 XML파일 하나 만들어 보자
(파일명은 test.xml로 하자.)
<?xml version="1.0" encoding="utf-8" ?> <config> <id>111.111.111.111</id> <user>vic</user> <pass>password</pass> </config>
일반적으로 많이 만들어 사용하는 콘피그 파일이다.
Linq이전에는 이녀석을 비교하려고 XML Document 열어서 열심히 While문으로 Read했었다.
Linq로 이놈을 한번 분석해보면 다음과 같이 매우 짧게 진행할 수 있다.
using System; using System.Linq; using System.Xml; using System.Xml.Linq;class Test { static void Main(){ XDocument xe = XDocument.Load(System.Windows.Forms.Application.StartupPath + "\\test.xml"); var query = from c in xe.Descendants("config") select c;
foreach(var q in query) { Console.WriteLine(q); } Console.ReadLine(); } }
실행시켜보면 위의 XML전체가 출력되는 것을 볼수 있을 것이다.
이제 이녀석을 좀더 다듬어 보자.
"select c;"라고 된 부분을 "select c.Element("id");"로 바꿔보자.
var query = from c in xe.Descendants("config") select c.Element("id");
실행을 하면 XML의 ID부분만 출력이 될 것이다.
<id>111.111.111.111</id>
어쩐지 제대로 찾아 들어오는 느낌. 이제 아까 바꾼 "select c.Element("id");"를
"select c.Element("id").Value;"로 바꿔보자.
var query = from c in xe.Descendants("config") select c.Element("id").Value;
실행하면 결과가 아주 이쁘게 값만 떨어진다.
111.111.111.111
그런데 여기서 만족할 수 없다. 여러개의 값을 가려오려면 어떻게 해야 할 까?
다음과 같이 함 바꿔보자.
var query = from c in xe.Descendants("config") select new { id = c.Element("id").Value, user = c.Element("user").Value } //이번에는 foreach문도 바꿔주자 foreach(var q in query) { Console.WriteLine(q.id + q.user); }
결과는 직접 함 해보도록하고 이제 다음단계로 SQL문처럼 한번 써보자.
다음과 같이 바꿔보고 실행 함 해보자.
var query = from c in xe.Descendants("config") where c.Element("user").Value == "vic" select c;
어떤게 나오는가? where문이 진짜 먹으니 뿌듯한 느낌!
2. XML생성
이제 한걸음 더 나가서 XML을 생성함 해보자.
사용은 무지 쉽다.
using System; using System.Linq; using System.Xml; using System.Xml.Linq;class Test { static void Main(){ XDocument xdoc = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XProcessingInstruction("TEST", "TEST Data"), new XComment("테스트 XML"), new XElement("config", new XElement("id", "1234"), new XElement("user", "abc") ) ); xdoc.Save(System.Windows.Forms.Application.StartupPath + "\\test.xml"); } }
test,xml을 열어 보면
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <?TEST TEST Data?> <!--테스트 XML--> <config> <id>1234</id> <user>abc</user> </config>
이렇게 정확하게 들어와 있는 것이 보일것이다.