관리 메뉴

심재운 블로그

LINQ 로 XDocument 클래스 사용해 보기 본문

닷넷관련/LINQ

LINQ 로 XDocument 클래스 사용해 보기

재우니 2015. 1. 8. 09:57

 

 

 

 

<?
xml version="1.0" encoding="utf-8" ?>
<People>
  <Person>
    <FirstName>Peter</FirstName>
    <LastName>Urda</LastName>
    <Age>21</Age>
    <Gender>M</Gender>
  </Person>
  <Person>
    <FirstName>Joe</FirstName>
    <LastName>White</LastName>
    <Age>30</Age>
    <Gender>M</Gender>
  </Person>
  <Person>
    <FirstName>Katie</FirstName>
    <LastName>Smith</LastName>
    <Age>25</Age>
    <Gender>F</Gender>
  </Person>
</People>

 

xml 이 호출되는 웹서비스 경로를 호출할때는 XDocument.Load() 함수를 통해 가져올 수 있고, xml 문자 글자를 파싱할때는 XDocument.Parse() 함수 사용하면 된다. Descendants 함수를 통해 하위 노드들을 가져올 수 있다.

 

여기서 linq 를 통해 구현이 가능하며 xml 관련 부분은 XDcoument 클래스를 사용해야 한다.

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace UsingXML
{
    // We establish a generic Person Class, and define necessary methods
    class PersonObject
    {
        public string fname { get; set; }
        public string lname { get; set; }
        public int age { get; set; }
        public char gender { get; set; }
 
        public PersonObject()
        {
            this.fname = null;
            this.lname = null;
            this.age = 0;
            this.gender = '0';
        }
        public PersonObject(string f, string l, int a, char g)
        {
            this.fname = f;
            this.lname = l;
            this.age = a;
            this.gender = g;
        }
    }
 
    class ReadAndLoad
    {
        // Declare a public XDocument for use
        public static XDocument XDoc;
 
        static void Main(string[] args)
        {
            // Prompt the user for file path, provide the current local
            // directory if the user wants to use a relative path.
            Console.Write("Current Local Path: ");
            Console.WriteLine(Environment.CurrentDirectory);
            Console.Write("Path to file? > ");
            string UserPath = Console.ReadLine();
  
            // Try to open the XML file
            try
            {
                Console.WriteLine("\nNow Loading: {0}\n", UserPath);
                XDoc = XDocument.Load(@UserPath);
            }
            // Catch "File Not Found" errors
            catch (System.IO.FileNotFoundException)
            {
                Console.WriteLine("No file found!");
                Environment.Exit(1);
            }
            // Catch Argument Exceptions
            catch (System.ArgumentException)
            {
                Console.WriteLine("Invalid path detected!");
                Environment.Exit(1);
            }
            // Catach all other errors, and print them to console.
            catch (Exception err)
            {
                Console.WriteLine("An Exception has been caught:");
                Console.WriteLine(err);
                Environment.Exit(1);
            }
 
            // Define a new List, to store the objects we pull out of the XML
            List<PersonObject> PersonList = new List<PersonObject>();
 
            // Build a LINQ query, and run through the XML building
            // the PersonObjects
            var query = from xml in XDoc.Descendants("Person")
                        select new PersonObject
                        {
                            fname = (string)xml.Element("FirstName"),
                            lname = (string)xml.Element("LastName"),
                            age = (int)xml.Element("Age"),
                            gender = ((string)xml.Element("Gender") == "M" ?
                                'M' :
                                'F')
                        };
            PersonList = query.ToList();
 
            // How many PersonObjects did we find in the XML?
            int ListSize = PersonList.Count;
 
            // Handle statements for 0, 1, or many PersonObjects
            if (ListSize == 0)
            {
                Console.WriteLine("File contains no PersonObjects.\n");
                Environment.Exit(0);
            }
            else if (ListSize == 1)
                Console.WriteLine("Contains 1 PersonObject:\n");
            else
                Console.WriteLine("Contains {0} PersonObjects:\n", ListSize);
 
            // Loop through the list, and print all the PersonObjects to screen
            for (int i = 0; i < ListSize; i++)
            {
                Console.WriteLine(" PersonObject {0}", i);
                Console.WriteLine("------------------------------------------");
                Console.WriteLine(" First Name : {0}", PersonList[i].fname);
                Console.WriteLine(" Last Name  : {0}", PersonList[i].lname);
                Console.WriteLine(" Age ...... : {0}", PersonList[i].age);
                Console.WriteLine(" Gender ... : {0}", PersonList[i].gender);
                Console.Write("\n");
            }
 
            // ...and we are done!
            Environment.Exit(0);
        }
    }
}

 

 

 

약간 추가로 말을 하자면..

 

아래처럼 returnCode, returnMsg 같은 별도로 하나의 값만 가지고 있을 경우엔, SingleOrDefault() 로 하나의 노드를 선택하고 Value 함수를 통해 값을 가져올 수 있다. 해당 노드가 없으면 null 로 반환이 된다.

 

var returnCode = (from e in XDoc.Descendants("returnCode") select e).SingleOrDefault().Value;
var returnMsg = (from e in XDoc.Descendants("returnMsg") select e).SingleOrDefault().Value;

 

 

 

 

 

 

 

 

 

 

0 Comments
댓글쓰기 폼