ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-415Interacting With Xml D…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-415

    Advanced Programming

    Progress0 / 55 done
    Topics55
    1Visual Programming Basics2Introduction to Events3Fundamentals of Event-Driven Programming4Message Handling5User Interfaces6Graphics Device Interface7Painting and Drawing8Windows Management9Input Devices10Resources11String and Menu Resource12Dialogs and Windows Controls13Common Controls14Dynamic Link Libraries (DLLs)15Threads and Synchronization16Network Programming17Building Class Libraries at the Command Line18Class Libraries19Using References20Assemblies21Private Assembly Deployment22Shared Assembly Deployment23Configuration Overview24Configuration Files25Programmatic Access to Configuration26Using SDK Tools for Signing and Deployment27Metadata28Reflection29Late Binding30Directories and Files31Serialization32Attributes33Memory Management and Garbage Collection34Threading and Synchronization35Asynchronous Delegates36Application Domains37Marshal by Value38Marshal by Reference39Authentication and Authorization40Configuring Security41Code Access Security42Code Groups43Evidence44Permissions45Role-Based Security46Principals and Identities47Using Data Readers48Using Data Sets49Interacting with XML Data50Tracing Event Logs51Using the Boolean Switch and Trace Switch Classes52Print Debugging Information with the Debug Class53Instrumenting Release Builds with the Trace Class54Using Listeners55Implementing Custom Listeners
    7 min read
    Topic 49 of 55
    Topic Study Note Illustration
    49

    Interacting with XML Data

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Advanced Programming