ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Interacting with XML Data
    Advanced ProgrammingTopic 49 of 55

    Interacting with XML Data

    7 minread
    1,253words
    Intermediatelevel

    Interacting with XML Data in ADO.NET

    XML (Extensible Markup Language) is widely used for storing and transporting data across different platforms and applications. ADO.NET provides extensive support for interacting with XML data, making it easy to load, manipulate, and update XML data in .NET applications. You can work with XML data in two primary ways: through DataSets and through direct XML processing using XML classes.

    Here’s a comprehensive guide on how to interact with XML data using ADO.NET.


    1. XML and DataSet

    A DataSet in ADO.NET has built-in support for XML, making it easy to read and write data in XML format. You can load XML data directly into a DataSet and also export a DataSet to XML.

    Key Features:

    • Load XML: You can load an XML document directly into a DataSet.
    • Export XML: You can export the content of a DataSet to an XML document.
    • Schema Support: A DataSet can optionally include an XML schema (XSD) that defines the structure of the data.

    2. Loading XML into a DataSet

    You can load an XML file or string into a DataSet using the ReadXml method.

    Example: Loading an XML File into a DataSet

    Suppose you have an XML file employees.xml with the following structure:

    <Employees>
      <Employee>
        <EmployeeID>1</EmployeeID>
        <FirstName>John</FirstName>
        <LastName>Doe</LastName>
        <Age>30</Age>
      </Employee>
      <Employee>
        <EmployeeID>2</EmployeeID>
        <FirstName>Jane</FirstName>
        <LastName>Smith</LastName>
        <Age>25</Age>
      </Employee>
    </Employees>
    

    Here is an example of how to load the XML data into a DataSet:

    using System;
    using System.Data;
    
    public class XmlDataSetExample
    {
        public void LoadXmlData()
        {
            // Create a new DataSet
            DataSet dataSet = new DataSet();
    
            // Load the XML data from a file
            dataSet.ReadXml("employees.xml");
    
            // Access the DataTable from the DataSet
            DataTable employeesTable = dataSet.Tables["Employees"];
    
            // Loop through the rows of the DataTable
            foreach (DataRow row in employeesTable.Rows)
            {
                Console.WriteLine($"Employee ID: {row["EmployeeID"]}, Name: {row["FirstName"]} {row["LastName"]}, Age: {row["Age"]}");
            }
        }
    }
    

    Explanation:

    • ReadXml: This method loads the XML data from the specified file into the DataSet. If you have an XML string, you can load that using ReadXml with a StringReader.
    • Tables["Employees"]: The ReadXml method automatically creates a DataTable for each root element in the XML document, based on the XML structure.
    • Looping Through Rows: You can access the data from the DataTable in the usual way, just like with any other table in a DataSet.

    3. Exporting DataSet to XML

    Once you have a DataSet, you can easily export it to an XML file or a string using the WriteXml method.

    Example: Exporting a DataSet to an XML File

    using System;
    using System.Data;
    
    public class ExportDataSetToXml
    {
        public void ExportData()
        {
            // Create a new DataSet and add a DataTable
            DataSet dataSet = new DataSet();
            DataTable employeesTable = new DataTable("Employees");
            dataSet.Tables.Add(employeesTable);
    
            // Add columns to the DataTable
            employeesTable.Columns.Add("EmployeeID", typeof(int));
            employeesTable.Columns.Add("FirstName", typeof(string));
            employeesTable.Columns.Add("LastName", typeof(string));
            employeesTable.Columns.Add("Age", typeof(int));
    
            // Add some rows to the DataTable
            employeesTable.Rows.Add(1, "John", "Doe", 30);
            employeesTable.Rows.Add(2, "Jane", "Smith", 25);
    
            // Export the DataSet to an XML file
            dataSet.WriteXml("exported_employees.xml");
    
            Console.WriteLine("Data has been exported to XML.");
        }
    }
    

    Explanation:

    • WriteXml: This method writes the contents of the DataSet to an XML file. You can also pass a stream (like a StringWriter) to write XML to a string.
    • Generated XML: The resulting XML file will include the data of the DataTable inside the DataSet, formatted with the table name as the root element.

    4. XML Schema and DataSet

    In addition to the data, you can also include the XML schema (XSD) when exporting the DataSet. The schema describes the structure of the XML data.

    Example: Exporting DataSet with Schema

    dataSet.WriteXml("employees_with_schema.xml");
    dataSet.WriteXmlSchema("employees_schema.xsd");
    
    • WriteXmlSchema: This method exports the schema (XSD) of the DataSet. The schema describes the structure of the XML document, such as the types of the columns and the relationships between tables.

    5. Modifying XML Data in a DataSet

    Once XML data is loaded into a DataSet, you can modify it just like any other data in a DataTable. You can add, update, or delete rows and columns in the DataTable.

    Example: Modifying XML Data in a DataSet

    using System;
    using System.Data;
    
    public class ModifyXmlData
    {
        public void ModifyData()
        {
            // Load the XML data into a DataSet
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("employees.xml");
    
            // Access the DataTable
            DataTable employeesTable = dataSet.Tables["Employees"];
    
            // Add a new row
            DataRow newRow = employeesTable.NewRow();
            newRow["EmployeeID"] = 3;
            newRow["FirstName"] = "Michael";
            newRow["LastName"] = "Johnson";
            newRow["Age"] = 28;
            employeesTable.Rows.Add(newRow);
    
            // Modify an existing row
            employeesTable.Rows[0]["Age"] = 31;  // Change John's age to 31
    
            // Delete a row
            employeesTable.Rows[1].Delete();  // Remove the second employee
    
            // Save the changes back to the XML file
            dataSet.WriteXml("modified_employees.xml");
    
            Console.WriteLine("XML data modified and saved.");
        }
    }
    

    Explanation:

    • Adding a New Row: NewRow creates a new row, and you can set values for each column.
    • Modifying Rows: Modify values in the existing rows by accessing the DataRow object.
    • Deleting Rows: Use the Delete method of DataRow to mark a row for deletion.
    • Saving Changes: After modifying the data, use WriteXml to save the updated DataSet to an XML file.

    6. Using LINQ to Query XML Data in a DataSet

    ADO.NET also supports LINQ queries on DataSet objects. You can use LINQ to query and filter data from the DataTable within the DataSet.

    Example: Using LINQ to Query XML Data

    using System;
    using System.Linq;
    using System.Data;
    
    public class LinqToXmlData
    {
        public void QueryXmlData()
        {
            // Load the XML data into a DataSet
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("employees.xml");
    
            // Access the DataTable
            DataTable employeesTable = dataSet.Tables["Employees"];
    
            // Use LINQ to query the data
            var employeesOver30 = from employee in employeesTable.AsEnumerable()
                                  where employee.Field<int>("Age") > 30
                                  select employee;
    
            foreach (var emp in employeesOver30)
            {
                Console.WriteLine($"Employee ID: {emp["EmployeeID"]}, Name: {emp["FirstName"]} {emp["LastName"]}, Age: {emp["Age"]}");
            }
        }
    }
    

    Explanation:

    • AsEnumerable: Converts the DataTable to an IEnumerable<DataRow>, allowing you to use LINQ methods on the data.
    • Field<T>: A LINQ method that allows you to access data from a DataRow in a strongly-typed manner.

    7. Working with XML Data Directly Using XmlDocument

    While the DataSet provides a powerful, table-oriented approach to XML data, you can also work with XML directly using the XmlDocument class. This class allows you to load, modify, and save XML data at a lower level, offering full flexibility for navigating and manipulating XML elements.

    Example: Using XmlDocument to Load and Manipulate XML

    using System;
    using System.Xml;
    
    public class XmlDocumentExample
    {
        public void ManipulateXml()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("employees.xml");
    
            // Access XML nodes
    
    Previous topic 48
    Using Data Sets
    Next topic 50
    Tracing Event Logs

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,253
      Code examples0
      DifficultyIntermediate