상세 컨텐츠

본문 제목

asp.net DB연동하여 결과물 xml 형태로 출력하기

Programming/asp.net

by luckey 2011. 9. 29. 14:00

본문

System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(this.Response.OutputStream, System.Text.Encoding.UTF8);
writer.Formatting = System.Xml.Formatting.Indented;

writer.WriteStartDocument(); //문서시작
writer.Indentation = 4;

writer.WriteStartElement("channel"); //<channel>

DataSet ds = new DataSet();
ds = 데이터불러와서 넣기

foreach (DataRow dr in ds.Tables[0].Rows)
{
    writer.WriteStartElement("item");
        writer.WriteAttributeString("text", "텍스트"); //<item text="텍스트"> -- 상위노드에 속성추가
        writer.WriteElementString("title", dr["title"].ToString()); //<title>dr["title"].ToString()</title> -- title 노드추가
        writer.WriteElementString("link", dr["link"].ToString()); //<link>dr["link"].ToString()</link> -- link 노드추가
    writer.WriteEndElement(); //</item>
}

writer.WriteEndDocument(); //</channel>


Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/xml";
writer.Flush(); //버퍼닫기
writer.Close(); //문서종료


--- 결과출력 ---
<?xml version="1.0" encoding="UTF-8">
<channel>
    <item text="텍스트">
        <title>제목1</title>
        <link>링크1</link>
    </item>
</channel>

관련글 더보기

댓글 영역