XML Handling Part 3 - Editing an XML

Όνομα: *
Το email μου: *
Email παραλήπτη: *
Μήνυμα: *
Τα πεδία με έντονους χαρακτήρες είναι υποχρεωτικά.
Δεν έχετε συμπληρώσει όλα τα απαιτούμενα στοιχεία Το email που δώσατε δεν είναι σωστό

In the previous articles we had quite a lot of talk about XMLs. We learned what XML is, how to read and create XML files. We also talked about XMLDocument. In this article, the last one of the XML series, we are going to use XMLDocument to update existing XML files.
 

Edit XML values

edit XML values
 
We are going to use an XML, similar to the one we have been using all along.
 
<?xml version="1.0" encoding="utf-8"?>
<SmsDataSet>
  <Sms>
    <Id>0</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Good morning!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-05T21:11:19.075+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>1</Id>
    <Numbers>+306931234567</Numbers>
    <Body>How are you?</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-07T07:47:48.005+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>2</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Bon Voyage!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-09T20:24:19.069+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
</SmsDataSet>
 
The way to edit is quite simple.
  1. Create an XMLDocument object.
  2. Load the XML we want to update
  3. Select the nodes we want to update.
  4. Update the nodes
  5. Save the XMLDocument object.
 
Here's a simple example to see how it works. This code will select the SMS node having Id = 2, and update its Body value to "Updated Value". We use ChildNodes[2], because we know that Body element is the third element within an Sms node. We have to use integer indexing as XmlNodeList does not allow selecting using string values.
 
    bool UpdateXMLValues()
    {
        bool success = true;
 
        try
        {
            string xmlFile = Server.MapPath("XMLFile.xml");
            // Load the XML file into an XmlDocument.
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);
 
            //Get a list of nodes based on their tag name, where Id = 2, using a filter
            XmlNodeList nodes = doc.SelectNodes("/SmsDataSet/Sms[Id=2]");
            foreach (XmlNode node in nodes)
                node.ChildNodes[2].InnerText = "Updated Value";
            //We could use the following line if we wanted to update attribute values
            //    node.SetAttribute("attr", "attribute");
 
            doc.Save(xmlFile);
        }
        catch(Exception ex)
        {
            success = false;
        }
 
        return success;
    }
 
The result will be
 
 
<?xml version="1.0" encoding="utf-8"?>
<SmsDataSet>
  <Sms>
    <Id>0</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Good morning!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-05T21:11:19.075+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>1</Id>
    <Numbers>+306931234567</Numbers>
    <Body>How are you?</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-07T07:47:48.005+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>2</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Updated Value</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-09T20:24:19.069+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
</SmsDataSet>
 
 

Insert XML values

adding XML values
 
We are now going to insert a new node within our XML. It's not much different than updating existing nodes. Here's what we need.
 
  1. Create an XMLDocument object.
  2. Load the XML we want to update
  3. Select the parent node we will place the new node.
  4. Create the node and insert info
  5. Append the new node to the parent node
  6. Save the XMLDocument object.
 
In the example we are going to insert a new Sms node. First, we select the SmsDataSet node. This will be our parent node. Then, we create a new Sms node using the CreateElement method. We go on, creating the inner nodes (Id, Numbers etc). We append all new nodes to the Sms node using the AppendChild method. Finally we append the Sms node to the parent SmsDataSet node.  
 
Since there is an Id node that should get an auto increment value, we compute the number of Sms nodes and place its number in the Id value of the new node. 
 
    bool InsertXMLValues()
    {
        bool success = true;
 
        try
        {
 
            string xmlFile = Server.MapPath("XMLFile.xml");
            // Load the XML file into an XmlDocument.
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);
 
            //Get the number of nodes to compute the new Id
            int numberOfSms = doc.SelectNodes("/SmsDataSet/Sms").Count;
 
            //Get the parent node
            XmlNode node = doc.SelectSingleNode("/SmsDataSet");
            //Create the new element
            XmlNode newNode = doc.CreateElement("Sms");
 
            //Create and fill inner elements
            XmlNode newNodeId = doc.CreateElement("Id");
            newNodeId.InnerText = (numberOfSms).ToString();
            XmlNode newNodeNumbers = doc.CreateElement("Numbers");
            newNodeNumbers.InnerText = "+31028237923";
            XmlNode newNodeBody = doc.CreateElement("Body");
            newNodeBody.InnerText = "New Node! Yeah!";
            //Include more elements
            // ........
 
            //Append inner elements to the new element
            newNode.AppendChild(newNodeId);
            newNode.AppendChild(newNodeNumbers);
            newNode.AppendChild(newNodeBody);
            //Append more elements
            // ........
 
            //Append the new element to the parent
            node.AppendChild(newNode);
 
            //Save the file
            doc.Save(xmlFile);
        }
        catch (Exception ex)
        {
            success = false;
        }
 
        return success;
    }
 
The result will be
 
<?xml version="1.0" encoding="utf-8"?>
<SmsDataSet>
  <Sms>
    <Id>0</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Good morning!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-05T21:11:19.075+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>1</Id>
    <Numbers>+306931234567</Numbers>
    <Body>How are you?</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-07T07:47:48.005+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>2</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Updated Value</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-09T20:24:19.069+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>3</Id>
    <Numbers>+31028237923</Numbers>
    <Body>New Node! Yeah!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-10T20:04:31.002+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
</SmsDataSet>
 
 

Delete XML values

delete XML values
 
Last thing to do, is learn how to remove a node. Once again we follow these simple steps.
 
  1. Create an XMLDocument object.
  2. Load the XML we want to update
  3. Select the parent node out of which we will remove the node.
  4. Select the node we are about to remove
  5. Remove the selected node from the parent node
  6. Save the XMLDocument object.
 
We want to delete the Sms node we created in the previous example. So, we select the parent SmsDataSet node and we remove the nodes we want ("/SmsDataSet/Sms[Id=3]") using the RemoveChild method.
 
 
bool DeleteXMLValues()
    {
        bool success = true;
 
        try
        {
 
            string xmlFile = Server.MapPath("XMLFile.xml");
            XmlDocument doc = new XmlDocument();
            // Load the XML file into an XmlDocument.
            doc.Load(xmlFile);
 
            //Select the parent node
            XmlNode node = doc.SelectSingleNode("/SmsDataSet");
            //Select the node that will be deleted
            XmlNodeList nodesToDelete = doc.SelectNodes("/SmsDataSet/Sms[Id=3]");
 
            foreach (XmlNode nodeToDelete in nodesToDelete)
                //Remove the node
                node.RemoveChild(nodeToDelete);
 
            //Since each node has unique Id, we could also use
            //XmlNode nodeToDelete = doc.SelectSingleNode("/SmsDataSet/Sms[Id=3]");
            //Remove the node
            //node.RemoveChild(nodeToDelete);
 
            //Save the file
            doc.Save(xmlFile);
 
        }
        catch (Exception ex)
        {
            success = false;
        }
 
        return success;
    }
 
As expected, the result is 
 
<?xml version="1.0" encoding="utf-8"?>
<SmsDataSet>
  <Sms>
    <Id>0</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Good morning!</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-05T21:11:19.075+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>1</Id>
    <Numbers>+306931234567</Numbers>
    <Body>How are you?</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-07T07:47:48.005+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
  <Sms>
    <Id>2</Id>
    <Numbers>+306931234567</Numbers>
    <Body>Updated Value</Body>
    <SmsType>0</SmsType>
    <Time>2012-02-09T20:24:19.069+02:00</Time>
    <ThreadId>3</ThreadId>
    <Status>2</Status>
    <ChatType>0</ChatType>
  </Sms>
</SmsDataSet>
 
 
 

Summary

This was the last article discussing XML handling. This time, we found out how we can update an XML file. We used XMLDocument to easily edit, insert and delete nodes by first selecting the appropriate nodes and then assign methods such as AppendChild or RemoveChild.

Πίσω στο BlogΠροηγούμενοΕπόμενο

Σχόλια



    Γράψε το σχόλιό σου
    Όνομα: