Notes Index
Working with XML
Extensible Markup Language (XML) is the preferred language of data interchange between ASP.NET Web Services and its consumer applications.
Given XML's flexibility, many organizations have developed XML markup language specifications. In addition, XML is used behind the scenes with many applications (e.g. Office 2007 stores its data files in a dialect of XML).
Activity 1: Creating a blank VS Solution to hold 2 Projects
Create a VS Solution to contain a Web Service Project and a Web Site Project
- Start up Visual Studio 2008
- Click Tools -> Options -> Projects and Solutions -> General -> check Always Show Solution
- Use the File menu to create a New Project
- In the Project types pane, expand Other Project Types and then select Visual Studio Solutions
- Chose Blank Solution and name it
U:\Day8
Activity 2: Add a Web Service to your Solution
Add a Web Service and a XML data file to your soluton
- Right click your Day8 solution and add a ASP.NET Web Service and place it at
U:\Day8\Day8Service
- Delete the default Service.asmx and Service.cs file
- Add a new Web Service item named
CustomerService.asmx
- Right click the App_Data folder and add a new XML Data file named
Customers.xml
- Copy and paste the XML data below into your
Customers.xml file
- Build your Web service to remove any compiler errors
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer id="c101">
<Name>
<FirstName>Ed</FirstName>
<LastName>Gellenbeck</LastName>
</Name>
</Customer>
<Customer id="c107">
<Name>
<FirstName>Fred</FirstName>
<MiddleInitial>T</MiddleInitial>
<LastName>Stanley</LastName>
</Name>
</Customer>
<Customer id="c103">
<Name>
<FirstName>Jim</FirstName>
<LastName>Schwing</LastName>
</Name>
</Customer>
</Customers>
Using an XmlDocument
.NET's XmlDocument class (part of the System.XML namespace) is a handy way to work with XML data in a .NET application. It gives programmers the ability to load a XML document and access it through the Document Object Model (W3C's DOM).
Using the DOM, nodes in an XmlDocument may be inserted, updated, deleted, and moved. The disadvantage of using the DOM is that the entire XML document is loaded into memory, so if the XML document is very large, this could be a problem.
Activity 3: Load an XML file into an XmlDocument in your Web Service
- Open CustomerService.cs file in VS editor and add the namespace
Cs352.Day8
- Add the following
GetCustomers method to your CustomerService class
- Build your project and fix the compiler errors
- Test the method by viewing
CustomerService.asmx in the browser
[WebMethod]
public XmlNode GetCustomers()
{
// Declare and instantiate a new XmlDocument
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
// Get the path to the XML file
string xmlFile = Server.MapPath("App_Data/Customers.xml");
// Read the SML file into memory
doc.Load(xmlFile);
return doc;
}
Activity 4: Add a Web Site to Consume your Web Service
Add a Web Site to act as a Consumer of your Web Service
- Right click your Day8 solution and add a ASP.NET Web Site and place it at
U:\Day8\Day8WebSite
- Right click on the
Day8WebSite project and Add Web Reference to your project
- Choose "Web services in this solution"
- Select the
CustomerService Web service
- Click Add Reference button
- Open the
default.aspx page and add an asp:Button and an asp:TextBox to the page
- Set the Button's Text to "Get Customers"
- Set the TextBox's TextMode="MultiLine" Rows="20" Columns="80"
- Generate a button click event handler that assigns the TextBox1's Text property to display the XML node returned by GetCustomers
protected void Button1_Click(object sender, EventArgs e)
{
localhost.CustomerService proxy = new CustomerService();
XmlNode node = proxy.GetCustomers();
TextBox1.Text = node.OuterXml;
}
Using XPath to Access Nodes in an XML Document
XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document. W3Schools has a popular XPath Tutorial.
Activity 5: Use XPath to find a Customer by id
- Add the WebMethod below that accepts the string argument
customerId and returns the corresponding customer element
- Set a debugger breakpoint in the method and test the method with the debugger
[WebMethod]
public XmlNode GetCustomer(string customerId)
{
XmlNode allCustomers = GetCustomers();
string xpath = String.Format("/Customers/Customer[@id='{0}']", customerId);
XmlNode customer = allCustomers.SelectSingleNode(xpath);
return customer;
}
Activity 6: Add the corresponding Web Form to consume your method
- Add a new Web Form named Default2.aspx to the Day8WebSite
- Add a asp:TextBox and a asp:Button to the form
- The asp:TextBox will be used allow the user to enter a customer id
- Set the asp:Button Text to "Find Customer"
- Add a second TextBox below the user input area
- Set the TextBox2's TextMode="MultiLine" Rows="20" Columns="80"
- Generate a button click event handler that assigns the TextBox2's Text property to display the XML node returned by GetCustomers
[WebMethod]
public bool AddCustomer(string fName, string mInitial, string lName)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("App_Data/Customers.xml"));
//Create a new Customer, FirstName, and LastName element
// skipped MiddleInitial to save time
XmlElement customer = doc.CreateElement("Customer");
XmlElement first = doc.CreateElement("FirstName");
XmlElement last = doc.CreateElement("LastName");
// Assign values to FirstName and LastName elements
first.InnerText = fName;
last.InnerText = lName;
// Add FirstName, LastName elements and an id attribute to Customer
customer.AppendChild(first);
customer.AppendChild(last);
customer.SetAttribute("id", "c122");
//Get the root element
XmlElement root = doc.DocumentElement;
//Add (append to the end of root's children) the Customer element
root.AppendChild(customer);
//Save the XmlDocument
doc.Save(Server.MapPath("App_Data/Customers.xml"));
return true;
}
Activity 7: Allow the user to add themselves as a Customer
- Add three TextBoxes to allow the user to add themselves as a Customer
<p>
<label for="FirstNameTextBox">First Name: </label>
<asp:TextBox ID="FirstNameTextBox" Columns="20" Runat="server" />
</p>
<p>
<label for="MiddleInitialTextBox">Middle Initial: </label>
<asp:TextBox ID="MiddleInitialTextBox" Columns="2" Runat="server" />
</p>
<p>
<label for="LastNameTextBox">Last Name: </label>
<asp:TextBox ID="LastNameTextBox" Columns="20" Runat="server" />
</p>
<p>
<asp:Button ID="AddMeButton" Text="Add Me" Runat="server" />
</p>
- Add the method to handle the button click to call the Web Service
Using C# classes for XML elements
Quite often, it is useful to represent XML elements as C# classes inside our programs.
For example, a Customer class could be written, an instance of Customer would represent a particular customer in our application
public class Customer
{
//instance variables
private string firstName;
private string middleInitial;
private string lastName;
//Properties
public string FirstName { }
public string MiddleInitial { }
public string LastName { }
//Constructor method
public Customer( ) { }
}