XML을 DataTable로

IT/C# 2012. 8. 24. 16:40
1
2
3
4
System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
xdoc.LoadXml(xml);
XmlNodeList xnl = xdoc.GetElementsByTagName("SessionID");
XmlNodeList OpCode = xdoc.GetElementsByTagName("opcode");

위와 같이 복잡하게 XML을 파싱하지말고, 간단히 DataSet에 DataTable 형태로 정리해보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Data;
using System.IO;
using System.Xml;
 
namespace XML2DataTable
{
    class Program
    {
        String strXml @"<coninfo><header><programcd>S1230</programcd><usrnm>Richard Park</usrnm></header><info><dept>12</dept></info></coninfo>";
        DataSet ds = new DataSet("xmlDS");
        TextReader txtReader = new StringReader(strXML);
        XmlReader reader = new XmlTextReader(txtReader);
        ds.ReadXml(reader);
 
        string strXmlElement = ds.Tables["header"].Rows[0]["programcd"].ToString().Trim();
       // []안의 string Index는 대소문자 구분이다.
    }
}


간단하게 Parsing하여 DataTable 형태로 편하게 불러다 쓰자!!

Posted by lI헐헐Il
,