-1

I have this query, can we do CRUD operation on XML using Serialization and Deserialization (using system.xml.serialization library )

I know it can be done using other libraries like xmldocument,XMLWriter but just curious to know whether is there any way that we can perform CRUD using Serialization and Deserialization (using system.xml.serialization library )

I want make it clear here that by "CRUD" operation i mainly mean a part of XML not whole xml. I don't want to deserialize whole xml and update the object and serialize to get final xml. I want deserialize/serialize only that part which is needed not all.

Snziv Gupta
  • 1,016
  • 1
  • 10
  • 21

1 Answers1

0

Basically you mean: Converts Object to XML & Converts XML to Object. This can be performed by

using System.Xml.Serialization;

Lets just say you have a list as :

public List<Product> GetProductList()
{
    List<Product> list = new List<Product>(); 
    Product product = new Product(new Section[3]);
    product.Sections[0] = new Section("1", new Header[3]);
    product.Sections[0].Headers[0] = new Header("P1", "C1", "T1");
    product.Sections[0].Headers[1] = new Header("P2", "C2", "T2");

    product.Sections[1] = new Section("2", new Header[3]);
    product.Sections[1].Headers[0] = new Header("P1", "C1", "T1");
    product.Sections[1].Headers[1] = new Header("P2", "C2", "T2");
    list.Add(product);
    return list;
}

You can serialize it as :

private void Serialize()
{
    List<Product> list = GetProductList(); 
    XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
    TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));
    serializer.Serialize(tw, list);
    tw.Close();
}

And deserialize the same as :

public void DeSerialize()
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
    TextReader tr = new StreamReader(Server.MapPath("book1.xml"));

    List<Product> b = (List<Product>)serializer.Deserialize(tr);
    tr.Close(); 
    Foreach (Product product in b)
    {
        Response.Write(product.Sections[0].Name + ",");
        Response.Write(product.Sections[1].Name);
    }
}
Nishant Singh
  • 3,055
  • 11
  • 36
  • 74
  • i agree to your answer but i am not looking for it ....may be i was unable to describe my issue ....so i am trying again – Snziv Gupta Dec 23 '15 at 12:59
  • The issue is when we deserialize the xml file we convert whole xml serialized data to object , so here comes my query suppose i have a very large XML file and i want to update a particular node or element, why should i deserialize whole xml for that and serialize it back for that small change ...isn't it wrong ....and in know thr are other ways using which my query can be solved but i was just curious to know to whether such small changes can be made in xml without overriding whole xml – Snziv Gupta Dec 23 '15 at 13:13