none
Format a LINQ object into XML RRS feed

  • Question

  • Dear All,

    After query the database and returned an object, is there a simple way for me to convert this object into XML string?

    Say for example, I have a table with columns below:

    TblProduct
    - Name
    - Price

    After select the above object into a LINQ object, I wish to convert it into XML string. Something like:

    <TblProduct>
        <Name>Bag</Name>
        <Price>123.45</Price>
    </TblProduct>

    Certainly the above XML string (node name) is for illustration purpose only. As long as LINQ can convert the object into XML string will be good for my need.
    Tuesday, October 27, 2009 9:29 AM

Answers

  • Take a look at the DataContractSerializer... You need to set serialization mode to "unidirectional" in the L2S designer's datacontext properties first, and then you can:


    TblProduct prod = dc.TblProducts.First();
    System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(prod.GetType());
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    ser.WriteObject(ms, prod);
    string someString = System.Text.Encoding.UTF8.GetString(ms.ToArray());
    


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for Visual Studio 2008's L2S and EF designers)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    • Marked as answer by Zhipeng Lee Monday, November 2, 2009 1:53 AM
    Tuesday, October 27, 2009 10:12 AM
    Answerer

All replies

  • Take a look at the DataContractSerializer... You need to set serialization mode to "unidirectional" in the L2S designer's datacontext properties first, and then you can:


    TblProduct prod = dc.TblProducts.First();
    System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(prod.GetType());
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    ser.WriteObject(ms, prod);
    string someString = System.Text.Encoding.UTF8.GetString(ms.ToArray());
    


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for Visual Studio 2008's L2S and EF designers)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    • Marked as answer by Zhipeng Lee Monday, November 2, 2009 1:53 AM
    Tuesday, October 27, 2009 10:12 AM
    Answerer
  • Are you looking for a generic solution that can transform any LINQ to SQL object into XML? Or do you simply want to know how to code that for a particular sample? In the latter case you can use LINQ to XML e.g.

    string xml = new XElement("TblProduct",
       new XElement("Name", obj.Name),
       new XElement("Price", obj.Price)).ToString();

    MVP XML My blog
    Tuesday, October 27, 2009 6:48 PM