본문 바로가기
Development/XML

XML 파싱 하기

by KingCat 2011. 4. 29.

우선 XML 파일이 필요하다.

<?xml version="1.0" encoding="utf-8" ?>
<ipConfiguration>
  <IP>
    <IPType>ServerIP</IPType>
    <IPAddress>000.000.000.000</IPAddress>
  </IP>
  <IP>
    <IPType>DatabaseIP</IPType>
    <IPAddress>000.000.000.000</IPAddress>
  </IP>
  <IP>
    <IPType>MyIP</IPType>
    <IPAddress>000.000.000.000</IPAddress>
  </IP>
</ipConfiguration>

IP 관리를 위한 XML 파일을 만들었다. ServerIP와 DatabaseIP, MyIP를 만들고 값을 000.000.000.000으로 적어놓았다.

using System.Xml;

private IP getIP()
{

IP ip = new IP();

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Server.MapPath("IpConfiguration.xml"));

            XmlElement elementlist = xmlDocument.DocumentElement;

            foreach (XmlNode node in elementlist.ChildNodes)
            {
                foreach (XmlNode lownode in node)
                {
                    if ((lownode.Name == "IPType") && (lownode.InnerText == "ServerIP"))
                    {
                        ip.ServerIP = node["IPAddress"].InnerText;
                    }
                    else if ((lownode.Name == "IPType") && (lownode.InnerText == "DatabaseIP"))
                    {
                        ip.DatabaseIP = node["IPAddress"].InnerText;
                    }
                    else if ((lownode.Name == "IPType") && (lownode.InnerText == "MyIP"))
                    {
                        ip.MyIP = node["IPAddress"].InnerText;
                    }
                }
            }

return ip;

}

이런식으로 사용했다. IP 클래스는 IP를 저장하는 클래스이고, Server.MapPath를 이용해서 xml 파일을 로드했다. 따로 경로가 필요하지는 않다. 코드가 있는 경로와 같은 곳에 xml이 있기 때문이다. foreach를 통해 하위 node까지 접근하고 하위 node의 Name과 값을 이용해서 필요한 값을 찾고 클래스에 저장하고 있다.