본문 바로가기

.Net

List to Xml - List to XDocument


Repository를 통해 받아온 List<SomeModel> 객체를 XML로 변형하는 방법.

- Serialization 을 통한 변환
private XDocument SomeListToXDocument(List<SomeModel> someList)
{
 MemoryStream ms = new System.IO.MemoryStream();
 XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
 
 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<SomeModel>));
 writer.Formatting = System.Xml.Formatting.Indented;
 writer.IndentChar = ' ';
 writer.Indentation = 3;
 
 serializer.Serialize(writer, someList);
 
 byte[] Result = new byte[ms.Length];
 ms.Position = 0;
 ms.Read(Result, 0, (int)ms.Length);
 
 return XDocument.Parse(Encoding.UTF8.GetString(Result, 0, (int)ms.Length));
}

 - Account controller Logon Action
public ActionResult logon()
{
    List<SomeModel> someList = getSomeListFromRepository();
    session["someList"] = SomeListToXDocument(someList);
    return view();
}

- View 페이지

<%@ Page Title="" Language="C#"  %>
<%
System.Xml.Linq.XDocument SomeList = null;
IEnumerable<System.Xml.Linq.XElement> query = null;

try
{
    MenuList = Session["SomeList"] as System.Xml.Linq.XDocument;
    query = from somelist in SomeList.Element("ArrayOfSomeCompositeModel").Elements("SomeCompositeModel")
            select somelist;
}
catch (Exception ex)
{
}

foreach (var item in query)
{
  Response.Write((string)item.Element("SOME_ID") + " / " (string)item.Element("SOME_NAME"));
}
%>