Covert Froma ArrayList to Serializable Xml RRS feed

  • Question

  • User-1399352090 posted


    I'm trying to convert from arraylist return funtion to xml.

    Code Behind:

    public static ArrayList ListofShops()
      ArrayList() _shops = new ArrayList();
     _shops.Add(new Shop(1,"KFC"));
    _shops.Add(new Shop(2,"MC"));
    return _shops;

    Generate Xml using ArrayList

     string strXML = string.Empty;
                ArrayList list= Shop.ListofShops();
                StringWriter sw = new StringWriter();
                XmlSerializer s = new XmlSerializer(typeof(ArrayList), new Type[] { typeof(Shop) });
                s.Serialize(sw, list);
                strXML = sw.ToString();
                return strXML;

    Everything is fine. But, it is Generating ArrayOfAnyType with anyType.


    <?xml version=\"1.0\" encoding=\"utf-16\"?>
    <ArrayOfAnyType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <anyType xsi:type=\"Shop\"> <ShopId>1</ShopId> <ShopName>KFC</ShopName> </anyType> <anyType xsi:type=\"Shop\"> <ShopId>2</ShopId> <ShopName>MC</ShopName> </anyType> </ArrayOfAnyType>"

    I want to show root as "Shops" and Item As "Shop"


    <?xml version=\"1.0\" encoding=\"utf-16\"?>
     <ShopId>1</ShopId> <ShopName>KFC</ShopName> 
    <ShopId>2</ShopId> <ShopName>MC</ShopName> 

    How can i add root names and item name?

    Please help me, Appropriate for quick and best response.

    Monday, March 30, 2015 10:12 AM


  • User61956409 posted

    Hi Yasin,

    Thanks for your post.

    It seems that you’d like to modify the nodes name of xml string, if that is the case, you could refer to the following code.

    string strXML ="<?xml version=\'1.0\' encoding=\'utf-16\'?><ArrayOfAnyType xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'><anyType xsi:type=\'Shop\'><ShopId>1</ShopId> <ShopName>KFC</ShopName></anyType><anyType xsi:type=\'Shop\'><ShopId>2</ShopId> <ShopName>MC</ShopName> </anyType></ArrayOfAnyType>";
    string str1 = strXML.Replace("ArrayOfAnyType", "Shops");
    string str2 = str1.Replace("anyType", "Shop");
    string STR = str2; 

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 31, 2015 1:26 AM