Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 45 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
45
Dung lượng
1,03 MB
Nội dung
Clicking the btnEdit button calls the btnEdit_Click sub: Private Sub btnEdit_Click(sender As Object, e As EventArgs) selectedDVD.childNodes(0).InnerText = txtTitle.text selectedDVD.childNodes(1).InnerText = txtFormat.text selectedDVD.childNodes(2).InnerText = txtGenre.text myXmlDocument.Save(Server.Mappath("dvd.xml")) lblMessage.text = "You have successfully updated the DVD" End Sub This subroutine sets the InnerText value from the values entered into the text fields. It then uses the Save() method to update the dvd.xml document and displays a message. As before, you need to make sure that you’ve set the appropriate permissions to allow updating. PHP: Modifying DVD Information You can use the form on the page editDVD.php to collect the modifications, which will then be processed with the page editDVDAction.php. The page editDVD.php populates the form with the selected element: <?php $id = $_GET['id']; $dom = new DomDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load("dvd.xml"); $path = "/library/DVD[@id=" . $id . "]"; $xPath = new domxpath($dom); $selectedNode = $xPath->query($path)->item(0); foreach ($selectedNode->childNodes as $child) { if ($child->nodeName == "title") { $title = $child->textContent; } elseif ($child->nodeName == "format") { $format = $child->textContent; } elseif ($child->nodeName == "genre") { $genre = $child->textContent; } } ?> <html> <head> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML 341 6765CH11.qxd 5/19/06 11:44 AM Page 341 <h1>Edit DVD Details</h1> <form id="frmEditDVD" method="POST" action="editDVDAction.php"> <input type="hidden" name="txtID" value="<?php echo $id; ?>"/> <table> <tr> <td class="emphasis">Title:</td> <td><input name="txtTitle" type="text" size="30" maxlength="50" value="<?php echo $title; ?>"/></td> </tr> <tr> <td class="emphasis">Format:</td> <td><input name="txtFormat" type="text" size="30" maxlength="50" value="<?php echo $format; ?>"/></td> </tr> <tr> <td class="emphasis">Genre:</td> <td><input name="txtGenre" type="text" size="30" maxlength="50" value="<?php echo $genre; ?>"/></td> </tr> <tr> <td class="emphasis" colspan="2"> <input type="submit" id="btnAdd" value="Update DVD"/> </td> </tr> </table> </form> </body> </html> The section within the <html></html> tags is similar to the previous PHP example, so I’ll focus on the processing code at the top of the page. The code starts by collecting the id from the querystring: <?php $id = $_GET['id']; It creates a new DomDocument object, sets the preserveWhiteSpace and formatOutput prop- erties, and loads the file dvd.xml. There is nothing new in this code block: $dom = new DomDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load("dvd.xml"); The next line creates an XPath expression and stores it in a variable called $path: $path = "/library/DVD[@id=" . $id . "]"; The expression finds the <DVD> element with the matching id attribute: /library/DVD[@id=1] CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML342 6765CH11.qxd 5/19/06 11:44 AM Page 342 The code then creates a new dompath object and uses it to return a NodeList with match- ing elements. The code selects the first element from the list: $xPath = new domxpath($dom); $selectedNode = $xPath->query($path)->item(0); The last block is a loop that checks the names of each of the child nodes of the <DVD> ele- ment. The code stores each value in a different variable using the PHP shorthand property textContent to access the text inside the element: foreach ($selectedNode->childNodes as $child) { if ($child->nodeName == "title") { $title = $child->textContent; } elseif ($child->nodeName == "format") { $format = $child->textContent; } elseif ($child->nodeName == "genre") { $genre = $child->textContent; } } ?> The page could have located the elements using other coding approaches. Using this approach allows me to show you how to use the domxpath object and different DOM scripting methods and properties. The page displays the values in the form elements: <form id="frmEditDVD" method="POST" action="editDVDAction.php"> <input type="hidden" name="txtID" value="<?php echo $id; ?>"/> <table> <tr> <td class="emphasis">Title:</td> <td><input name="txtTitle" type="text" size="30" maxlength="50" value="<?php echo $title; ?>"/></td> </tr> <tr> <td class="emphasis">Format:</td> <td><input name="txtFormat" type="text" size="30" maxlength="50" value="<?php echo $format; ?>"/></td> </tr> <tr> <td class="emphasis">Genre:</td> <td><input name="txtGenre" type="text" size="30" maxlength="50" value="<?php echo $genre; ?>"/></td> </tr> <tr> <td class="emphasis" colspan="2"> <input type="submit" id="btnAdd" value="Update DVD"/> CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML 343 6765CH11.qxd 5/19/06 11:44 AM Page 343 </td> </tr> </table> </form> Notice that I’ve also passed through the id in a hidden form field. Again, I haven’t added validation to simplify the code. Once the user changes the details of a DVD, the form submits to the page editDVDAction.php: <?php $id = $_POST['txtID']; $title = $_POST['txtTitle']; $format = $_POST['txtFormat']; $genre = $_POST['txtGenre']; $dom = new DomDocument(); $dom->load("dvd.xml"); $path = "/library/DVD[@id=" . $id . "]"; $xPath = new domxpath($dom); $selectedNode = $xPath->query($path)->item(0); foreach ($selectedNode->childNodes as $child) { if ($child->nodeName == "title") { $child ->firstChild->nodeValue = $title; } elseif ($child->nodeName == "format") { $child->firstChild->nodeValue = $format; } elseif ($child->nodeName == "genre") { $child->firstChild->nodeValue = $genre; } } $dom->save("dvd.xml"); ?> <html> <head> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="divMessage">You have successfully updated the XML document</div> </body> </html> CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML344 6765CH11.qxd 5/19/06 11:44 AM Page 344 The code starts by collecting the values posted from the form and storing them in variables: <?php $id = $_POST['txtID']; $title = $_POST['txtTitle']; $format = $_POST['txtFormat']; $genre = $_POST['txtGenre']; Again, the code creates a new DomDocument and loads the dvd.xml document: $dom = new DomDocument(); $dom->load("dvd.xml"); The code uses the same approach as on the previous page, using a domxpath object to find the selected <DVD> element: $path = "/library/DVD[@id=" . $id . "]"; $xPath = new domxpath($dom); $selectedNode = $xPath->query($path)->item(0); The code loops through the child nodes of the <DVD> element and applies the updates: foreach ($selectedNode->childNodes as $child) { if ($child->nodeName == "title") { $child ->firstChild->nodeValue = $title; } elseif ($child->nodeName == "format") { $child->firstChild->nodeValue = $format; } elseif ($child->nodeName == "genre") { $child->firstChild->nodeValue = $genre; } } Notice that the code assigns the value to the nodeValue property of the firstChild of the selected element. It’s important to do this because the text within an element is the firstChild of that element. Finally, the code saves the changes: $dom->save("dvd.xml"); ?> CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML 345 6765CH11.qxd 5/19/06 11:44 AM Page 345 Deleting a DVD The last task for the application is removing a DVD from the library. The application passes the id of the element that will be removed to either the deleteDVD.aspx or deleteDVD.php page. .NET: Deleting a DVD The deleteDVD.aspx page follows: <%@ Page Language="VB" %> <%@ import Namespace="System.Xml" %> <script runat="server"> Dim intDVDID as integer Dim myXmlDocument as XmlDocument = new XmlDocument() Dim rootNode as XMLElement Dim selectedDVD as XMLElement Sub Page_Load(Src As Object, E As EventArgs) intDVDID = request.querystring("id") myXmlDocument.Load (server.mappath("dvd.xml")) rootNode = myXmlDocument.DocumentElement selectedDVD = rootNode.childNodes(intDVDID-1) if Not Page.IsPostBack then rootNode.RemoveChild(selectedDVD) myXmlDocument.Save(Server.Mappath("dvd.xml")) lblMessage.text = "You have successfully deleted the DVD" end if end sub </script> <html> <head> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> <h1>Delete DVD</h1> <form runat="server"> <asp:Label id="lblMessage" runat="server" forecolor="Blue"></asp:Label> </form> </body> </html> This page is very simple. It starts with some declarations and variable definitions: <%@ Page Language="VB" %> <%@ import Namespace="System.Xml" %> <script runat="server"> Dim intDVDID as integer Dim myXmlDocument as XmlDocument = new XmlDocument() Dim rootNode as XMLElement Dim selectedDVD as XMLElement CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML346 6765CH11.qxd 5/19/06 11:44 AM Page 346 When the page loads, it determines the id of the DVD to delete and loads the XML document: Sub Page_Load(Src As Object, E As EventArgs) intDVDID = request.querystring("id") myXmlDocument.Load (server.mappath("dvd.xml")) The code sets a variable for the document element and identifies the <DVD> element to delete: rootNode = myXmlDocument.DocumentElement selectedDVD = rootNode.childNodes(intDVDID-1) It then removes the element, saves the dvd.xml document, and displays a success message: if Not Page.IsPostBack then rootNode.RemoveChild(selectedDVD) myXmlDocument.Save(Server.Mappath("dvd.xml")) lblMessage.text = "You have successfully deleted the DVD" end if end sub </script> PHP: Deleting a DVD from the List The deleteDVD.php page is also very simple: <?php $id = $_REQUEST['id']; $dom = new DomDocument(); $dom->load("dvd.xml"); $root = $dom->documentElement; $path = "/library/DVD[@id=" . $id . "]"; $xPath = new domxpath($dom); $DVDelement = $xPath->query($path)->item(0); $root -> removeChild($DVDelement); $dom->save("dvd.xml"); ?> <html> <head> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="divMessage">You have successfully updated the XML document</div> </body> </html> CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML 347 6765CH11.qxd 5/19/06 11:44 AM Page 347 The code block starts by determining the id of the <DVD> element to delete and then cre- ates a new DomDocument, loading the dvd.xml document: <?php $id = $_REQUEST['id']; $dom = new DomDocument(); $dom->load("dvd.xml"); The code then sets a variable, $root, for the document element and creates an XPath expression that targets the appropriate <DVD> element: $root = $dom->documentElement; $path = "/library/DVD[@id=" . $id . "]"; $xPath = new domxpath($dom); $DVDelement = $xPath->query($path)->item(0); Finally, the removeChild() method removes the element from the document element vari- able, and the code updates the XML document: $root -> removeChild($DVDelement); $dom->save("dvd.xml"); ?> Summary In this chapter, I showed you how to use server-side processing to work with XML documents. I examined the advantages of working on the server compared with client-side processing. You saw that you can apply transformations on the server and send only the transformed con- tent to the client. This approach reduces the amount of content sent to the client and avoids the need to code for different browser types and versions. The chapter gave a brief overview of using .NET 2.0 and PHP 5 to work with XML content. I worked through some simple examples showing how to perform common XML-related tasks. I looked briefly at • Applying an XSLT transformation to an XML document to create XHTML • Creating new elements and updating an external XML document • Modifying existing XML content • Deleting content from within an XML document Even though I only covered .NET and PHP, many of the DOM manipulation methods are similar to those used client-side. The techniques demonstrated within this chapter could apply equally to other server-side languages. In the next two chapters, I’ll look at each of the two approaches in more detail. CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML348 6765CH11.qxd 5/19/06 11:44 AM Page 348 Case Study: Using .NET for an XML Application In Chapter 11, you learned about many advantages to using XML on the server. You also saw that .NET has good support for XML. In this chapter, I’ll work through a .NET case study, so you can see some of the techniques available to you. In this case study, I’ll build a News application to display XML browser news. The applica- tion will show XML and web news from a Microsoft Access database, and users will be able to add news items. The site will make the news available as a Really Simple Syndication (RSS) 2.0 feed and will display feeds from other web sites. This application isn’t intended as a secure and robust case study. Rather, it’s an example of what you can achieve using .NET and XML on the server. You’ll start by learning more about how the application is structured. After that, I’ll work through each section of the application in detail. Understanding the Application In this case study, I’ll work with news items in a database and RSS feeds. If you’re not familiar with RSS, it describes news items using an XML vocabulary. Netscape originally developed RSS, and there are actually seven different specifications. In this example, I’ll focus on RSS 2.0. You can find out more about the RSS 2.0 specification at http://blogs.law.harvard.edu/ tech/rss. The application displays and manages news items stored in an Access database. It gener- ates an RSS 2.0 feed from these news items and uses an XSLT stylesheet to display them on the home page. Users can add, edit, and delete news items. They can also view and consume the RSS feed. The application allows users to display RSS 2.0 news feeds from other web sites. The same XSLT stylesheet transforms these feeds into XHTML for display on the page. 349 CHAPTER 12 6765CH12.qxd 5/19/06 11:58 AM Page 349 Figure 12-1 shows the application displaying the current XML browser news from the database. Users see this view when they first enter the site. Figure 12-1. The News application You can see that a link at the top right of the page allows users to manage news items. Users can also view the RSS feed by clicking the RSS 2.0 image button. Selecting a different news feed displays the news items on the page. Setting Up the Environment The case study uses .NET 2.0, so you need to run the Internet Information Services (IIS) web server on your computer or at your Internet service provider (ISP). You also need to have the .NET Framework 2.0 installed. You can download this at no cost from the Microsoft web site at http://msdn.microsoft.com/netframework/downloads/updates/default.aspx. You can’t use an earlier version of .NET because the application uses controls that are only available in .NET 2.0. I’ve written the application using Visual Basic .NET (VB .NET), but you could rewrite it using Visual C# .NET (C#), JavaServer Pages (JSP), or any of the other languages supported by the common language runtime (CLR). CHAPTER 12 ■ CASE STUDY: USING .NET FOR AN XML APPLICATION350 6765CH12.qxd 5/19/06 11:58 AM Page 350 [...]... method to flush whatever is in the buffer to the stream, and it uses the Close() method to close the stream: 6765CH12.qxd 5/ 19/ 06 11:58 AM Page 367 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION XMLFeed.WriteEndElement() XMLFeed.WriteEndElement() XMLFeed.WriteEndDocument() XMLFeed.Flush() XMLFeed.Close() Response.End() End sub The code creates the following structure: < ?xml version="1.0"... columns as command fields: 375 6765CH12.qxd 376 5/ 19/ 06 11:58 AM Page 376 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION These columns display Edit and Delete links automatically because the ShowEditButton and ShowDeleteButton properties... CType(NewsDS.Select(DataSourceSelectArguments.Empty), ➥ DataView) Dim XMLFeed as XmlTextWriter = new XmlTextWriter(Response.OutputStream, ➥ Encoding.UTF8) XMLFeed.WriteStartDocument() XMLFeed.WriteStartElement("rss") XMLFeed.WriteAttributeString("version", "2.0") XMLFeed.WriteStartElement("channel") XMLFeed.WriteElementString("title", "XML Browser News") XMLFeed.WriteElementString("link", "http://www.apress.com") XMLFeed.WriteElementString("description",... latest XML browser news.") For Each dr As DataRow In dv.Table.Rows 6765CH12.qxd 5/ 19/ 06 11:58 AM Page 365 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION XMLFeed.WriteStartElement("item") XMLFeed.WriteElementString("title", dr("newsTitle").ToString()) XMLFeed.WriteElementString("description", dr("newsDescription").ToString()) XMLFeed.WriteEndElement() Next XMLFeed.WriteEndElement() XMLFeed.WriteEndElement()... this element to 2.0: XMLFeed.WriteStartDocument() XMLFeed.WriteStartElement("rss") XMLFeed.WriteAttributeString("version", "2.0") Next, the code creates the element along with the , , and elements: XMLFeed.WriteStartElement("channel") XMLFeed.WriteElementString("title", "XML Browser News") XMLFeed.WriteElementString("link", "http://www.apress.com") XMLFeed.WriteElementString("description",... 351 6765CH12.qxd 352 5/ 19/ 06 11:58 AM Page 352 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION I could have added other fields such as publish and expiration dates, and used them to filter the display I could also have added links to pages containing more content However, the aim here is to create a simple application and focus on XML and NET Remember that you need to set appropriate write... SelectCommand property The code also specifies two additional SQL commands: UpdateCommand and DeleteCommand These commands specify which SQL statement to run when users click the Update or Delete links The UpdateCommand attribute refers to an UPDATE statement Notice that the code uses the wildcard character ? to specify that it will receive update parameters The @newsID placeholder specifies the newsID from. .. stylesheet is straightforward It starts with an XML declaration and element: < ?xml version="1.0" encoding="UTF-8"?> 361 6765CH12.qxd 362 5/ 19/ 06 11:58 AM Page 362 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION The stylesheet then matches the document element and applies the template for the ... application The new Xml control displays the XML content, and the GridView control allows for editing of the database content The application could use a Microsoft SQL Server 2005 or an Access database to store the news items SQL Server 2005 provides additional XML support compared with Access, and is obviously better suited to large-scale applications As the focus here is on scripting XML in NET, the... stream to Response.OutputStream and the encoding to UTF8 It could also specify a physical file for the XML stream 365 6765CH12.qxd 366 5/ 19/ 06 11:58 AM Page 366 CHAPTER 12 ■ CASE STUDY: USING NET FOR AN XML APPLICATION The next code section starts writing the XML stream, using the WriteStartDocument() method to generate the XML declaration The WriteStartElement() method creates the root element, and . new DomDocument and loads the dvd .xml document: $dom = new DomDocument(); $dom- >load("dvd .xml& quot;); The code uses the same approach as on the previous page, using a domxpath object to. creates a new DomDocument object, sets the preserveWhiteSpace and formatOutput prop- erties, and loads the file dvd .xml. There is nothing new in this code block: $dom = new DomDocument(); $dom- >preserveWhiteSpace. integer Dim myXmlDocument as XmlDocument = new XmlDocument() Dim rootNode as XMLElement Dim selectedDVD as XMLElement CHAPTER 11 ■ INTRODUCTION TO SERVER-SIDE XML3 46 6765CH11.qxd 5/ 19/ 06 11:44 AM