Update xml element in asp.net using linq

Hi Friends,

In my earlier post, we have seen that how can we delete xml element using linq to xml query.

you can check it from here

Today we will see how to update element in existing XML file.

For this, we need to load XML file from the disk, update the element and save the updated XML to the disk.

Let’s see how can we do this using below example.

see the below searched xml element:

 
   3
   Gautam
   bhatia
   30
 
 

I have searched xml element in my previous post for deleting it.
Now we will update last name for the Employee Gautam


.............
.............
first search the element employee from the emplyees.xml file
load it into xmlData variable
.............
.............

XDocument doc = XDocument.Load(XMLDocPath);
var xmlData = (from item in doc.Descendants("employee")
               select item).ToList();

foreach (var item in xmlData)
{
   item.Element("lastname").Value = "Gambhir";
}

doc.Save(XMLDocPath);

hope this will help you.

Delete xml element in asp.net using linq

Hello,

Today, in this article let’s play around with one of the interesting and most useful concepts in LINQ to XML.

LINQ to XML Delete functionality, we will see how to delete elements from existing XML file.

We will load an XML file from the disk, remove the elements and save the updated XML to the disk.

see the below example code of Employee.xml file:


  
    1
    Sachin
    Tendulkar
    41
  
  
    2
    Virender
    Sehwag
    35
  
 
   3
   Gautam
   Gambhir
   30
 
 
   4
   Yuvraj
   Singh
   33
 

Now we will remove the Element, for the Employee Gautam

    XDocument doc = XDocument.Load(XMLDocPath);

    doc.Root.Elements("Employees")
   .Where(p => p.Element("firstName").Value == "Gautam")
   .Remove();

   doc.Save(XMLDocPath);

After execution of this code, the Employee.xml file will looks like as below,


  
    1
    Sachin
    Tendulkar
    41
  
  
    2
    Virender
    Sehwag
    35
  
 
   4
   Yuvraj
   Singh
   33
 

That’s it we have deleted an Element from XML file and saved the changes to the Disk.

I hope this post is useful for you

Example of xml and xsl

Hello all,

All we know use of xml. Xml is use for store data it will consume less space and easy to transfer. But, most of us confuse in xsl use. Xsl is style sheet of xml. XSL is use to represent your xml data in html, pdf, doc or plain text. Without use of css how to represent xml data in html at that you can use xsl.

Today i want to share one simple example to understand xml and xsl. Following is xml we will use to transform in html.





SQL
http://www.blogfornet.com/sql/


HTML
http://www.blogfornet.com/html/


ASP.Net
http://www.blogfornet.com/asp-net/


C#
http://www.blogfornet.com/c-2/


Now, create following xsl file name with example.xsl.











XSL Example

That’s it. This is simple example of XML XSL use. We will discuss advance XSLT in next phase…

Reading XML file in c#

Hello friends,

Today i will show you an example of reading xml file. To generate xml file read my previous blog.

I know there are many ways to read xml. But today we will use xDocument to read xml file.

Following is xml file we have generated.



  
    0
    Sunil
    Gavaskar
    abc@xyz.com
    Sunil Gavaskar
    100
    2013-07-18
  

Now, to read this xml we will use following function.

        public string xmlRead()
        {
            try
            {
                StringBuilder xmlData = new StringBuilder();

                XmlDocument oReqDoc = new XmlDocument();
                oReqDoc.Load("c:/sendRequest.xml");

                XDocument rcvDoc = XDocument.Parse(oReqDoc.InnerXml);

                foreach (var itemTrn in rcvDoc.Descendants("Content").Descendants("Customer"))
                {

                    xmlData.AppendLine(" Gender = " + itemTrn.Element("Gender").Value.ToString());
                    xmlData.AppendLine(" Firstname = " + itemTrn.Element("Firstname").Value);
                    xmlData.AppendLine(" Lastname = " + Convert.ToString(itemTrn.Element("Lastname").Value));
                    xmlData.AppendLine(" Mail = " + Convert.ToString(itemTrn.Element("Mail").Value));
                    xmlData.AppendLine(" AccountName = " + Convert.ToString(itemTrn.Element("AccountName").Value));
                    xmlData.AppendLine(" Amount = " + Convert.ToInt64(itemTrn.Element("Amount").Value));
                    xmlData.AppendLine(" Currency = " + Convert.ToString(itemTrn.Element("Amount").Attribute("Currency").Value));
                    xmlData.AppendLine(" CollectDate = " + Convert.ToDateTime(itemTrn.Element("CollectDate").Value));

                    // your code goes here

                }
                return xmlData.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

In above code i have load xml document and parse it in xDocument. Then by Descendants method you can read xml data you want. Descendants method is use to read specific data element from xml documents.

Some have error like data at the root level is invalid. line 1 position 1 it will occurs when you are using LoadXML method. If you will getting this error use Load method and error will gone.

Hope, it will help you.

Genearate xml file in c#

To generate xml file we will use system.xml. There are many ways to generate xml file with xmlDocument with xdocument.

I have prepare one sample to generate xml file. Suppose we want to generate customer data xml as follow.



  
    0
    Sunil
    Gavaskar
    abc@xyz.com
    Sunil Gavaskar
    100
    2013-59-18
  

Use System.Xml and System.Xml.Linq namespace.
To generate above xml we will use following code.

        public void xmlGenerate()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, "encoding", "utf-8");
            doc.AppendChild(declaration);

            // Content element
            XmlElement content = doc.CreateElement("Content");
            doc.AppendChild(content);

            // Customer Element
            XmlElement customer = doc.CreateElement("Customer");
            content.AppendChild(customer);

            // Customer sub Element
            XmlElement gender = doc.CreateElement("Gender");
            //XmlText genderText = doc.CreateTextNode("0"); // 0= Unknown,1 = Male,2 = Female
            gender.InnerText = "0";
            customer.AppendChild(gender);
            //gender.AppendChild(genderText);

            // Customer sub Element
            XmlElement firstname = doc.CreateElement("Firstname");
            XmlText firstnameText = doc.CreateTextNode("Sunil");
            customer.AppendChild(firstname);
            firstname.AppendChild(firstnameText);

            // Customer sub Element
            XmlElement lastname = doc.CreateElement("Lastname");
            XmlText lastnameText = doc.CreateTextNode("Gavaskar");
            customer.AppendChild(lastname);
            lastname.AppendChild(lastnameText);

            // Customer sub Element
            XmlElement mail = doc.CreateElement("Mail");
            XmlText mailText = doc.CreateTextNode("abc@xyz.com");
            customer.AppendChild(mail);
            mail.AppendChild(mailText);

            // Customer sub element
            XmlElement accountName = doc.CreateElement("AccountName");
            XmlText accountNameText = doc.CreateTextNode("Sunil Gavaskar");
            customer.AppendChild(accountName);
            accountName.AppendChild(accountNameText);

            // Customer sub element
            XmlElement amount = doc.CreateElement("Amount");
            XmlText amountText = doc.CreateTextNode("100");
            customer.AppendChild(amount);
            amount.AppendChild(amountText);

            //Attribute amount
            XmlAttribute currency = doc.CreateAttribute("Currency");
            currency.Value = "EUR";
            amount.Attributes.Append(currency);

            // Customer sub element
            XmlElement collectDate = doc.CreateElement("CollectDate");
            XmlText collectDateText = doc.CreateTextNode(DateTime.Now.ToString("yyyy-mm-dd"));
            customer.AppendChild(collectDate);
            collectDate.AppendChild(collectDateText);

            doc.Save(@"c:/sendRequest.xml");

            // More customer then use below code and comment all xmlText node.
            //string xmlDoc = doc.InnerXml;
            //XDocument doc1 = XDocument.Parse(xmlDoc);

            //foreach (var itemCus in doc1.Descendants("Customer"))
            //{
            //    itemCus.Element("Gender").SetValue("0"); // 0= Unknown,1 = Male,2 = Female
            //    itemCus.Element("Firstname").SetValue("Sunil");
            //    itemCus.Element("Lastname").SetValue("Gavaskar");
            //    itemCus.Element("Mail").SetValue("abc@xyz.com");
            //    itemCus.Element("AccountName").SetValue("123456");
            //    itemCus.Element("Amount").SetValue("100");
            //    itemCus.Element("CollectDate").SetValue(DateTime.Now.ToString("yyyy-MM-dd"));
            //}

            //doc1.Save(@"c:/sendRequest.xml");
                        
        }

We can generate xml document from xmldocument. Save method save our xml file. XmlElement value or text save by two method first is use xmlTitle method or by node innerText method. We can set text by both way.

If you want to set text or value after generating xml document than use comment part. after generating xmlDocument element set it into xdocument. In xDocument set customer data by loop.

In next phase i will show you how to read xmlDocument.