C# .NET Web Developer''''s Guide phần 7 docx

82 316 0
C# .NET Web Developer''''s Guide phần 7 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

470 Chapter 9 • Working with XML Figure 9.11 shows the program after you click Run XPath Queries.When you click the button, the program does a number of queries against the per- sonnel.xml file and writes the results into the listbox on the form. Figure 9.12 shows a portion of the XML contained in the personnel.xml file used to gen- erate the queries. Figure 9.12 Generating Queries (personnel.xml) <?xml version="1.0" standalone="yes"?> <Employees> <Employee EmployeeID="1"> <FirstName>John</FirstName> <MiddleInit>M</MiddleInit> <LastName>Smith</LastName> <Salaried>true</Salaried> <Wage>40000</Wage> <Active>true</Active> <Title>Jr. Programmer</Title> <Location> <Address>103 N.72nd</Address> <City>Seattle</City> <State>WA</State> <Zip>98103</Zip> </Location> </Employee> <Employee EmployeeID="2"> <FirstName>Joe</FirstName> <MiddleInit>R</MiddleInit> <LastName>Jones</LastName> <Salaried>false</Salaried> <Wage>22.75</Wage> <Active>true</Active> <Title>Graphic Artist</Title> <Location> <Address>13222 S. 1st Avenue</Address> <City>Portland</City> www.syngress.com Continued Working with XML • Chapter 9 471 <State>OR</State> <Zip>97206</Zip> </Location> </Employee> Figure 9.13 contains the relevant portions of the source code for the XPath sample. Source code inserted by the Visual Studio.NET designer has been omitted. Figure 9.13 Relevant Portions of Source Code (XPathForm.cs) using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Xml; using System.Xml.XPath; using System.IO; namespace XPath { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; www.syngress.com Figure 9.12 Continued Continued 472 Chapter 9 • Working with XML private string m_strOutput; public Form1() { InitializeComponent(); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } /// <summary> /// Called when Run XPath Queries is pressed /// </summary> private void button1_Click(object sender, System.EventArgs e) { Cursor currentCursor = Cursor.Current; try { Cursor.Current = Cursors.WaitCursor; // Do XPath queries on both XPath Documents and // DOM-based XML documents doXPathDocumentQueries(); doXmlDocumentQueries(); // Show results on-screen www.syngress.com Figure 9.13 Continued Continued Working with XML • Chapter 9 473 textBox1.Text = m_strOutput; } catch ( Exception exception ) { MessageBox.Show( exception.Message ); } finally { Cursor.Current = currentCursor; } } /// <summary> /// Do XPath queries against a read-only XPathDocument /// </summary> private void doXPathDocumentQueries() { m_strOutput = "*** Beginning XPathDocument Queries ***\r\n\r\n"; // Load the XML document into a read-only XPathDocument // and instantiate a navigator for queries. XPathDocument doc = new XPathDocument( "personnel.xml" ); XPathNavigator navigator = doc.CreateNavigator(); m_strOutput += "*** Show All Wages ***\r\n\r\n"; // Find all Employee/Wage elements in the document and // display the wage information on-screen XPathNodeIterator iterator = navigator.Select( "descendant::Employee/Wage" ); www.syngress.com Figure 9.13 Continued Continued 474 Chapter 9 • Working with XML while ( iterator.MoveNext() ) { m_strOutput += iterator.Current.Name + ": "; m_strOutput += iterator.Current.Value + "\r\n"; } m_strOutput += "\r\n\r\n*** Show All Employees in Seattle ***\r\n\r\n"; // Find all employees in the Seattle office and display // their names on-screen iterator = navigator.Select( "//Employee[Location/Zip='98103']" ); while ( iterator.MoveNext() ) { XPathNavigator nav2 = iterator.Current; nav2.MoveToFirstChild(); m_strOutput += nav2.Value; // First name nav2.MoveToNext(); m_strOutput += ". " + nav2.Value; // Middle init nav2.MoveToNext(); m_strOutput += " " + nav2.Value + "\r\n"; // Last name } m_strOutput += "\r\n\r\n*** Salaried Employee Average Wage ***\r\n\r\n"; // Calculate the average salary for all salaried employees // in the company and display on-screen Int32 nAverage = (Int32)(Double)navigator.Evaluate( "sum(//Employee[Salaried='true']/Wage) div www.syngress.com Figure 9.13 Continued Continued Working with XML • Chapter 9 475 count(//Employee[Salaried='true'])" ); m_strOutput += "Average Salary: $" + nAverage.ToString(); } /// <summary> /// Do an XPath queries against a DOM-based XML document and then /// modify the document. /// </summary> private void doXmlDocumentQueries() { m_strOutput += "\r\n\r\n*** Beginning XML Document Query ***\r\n\r\n"; // Load the XML document into a DOM-based XML document XmlDocument doc = new XmlDocument(); doc.Load( "personnel.xml" ); // Get a list of the Active element nodes for each employee // in Portland XmlNodeList nodeList = doc.SelectNodes( "//Employee[Location/Zip='97206']/Active"); foreach ( XmlNode node in nodeList ) { // Mark each Portland employee as inactive node.InnerText = "false"; } // Display the modified document on-screen StringWriter writerString = new StringWriter(); XmlTextWriter writer = new XmlTextWriter( writerString ); www.syngress.com Figure 9.13 Continued Continued 476 Chapter 9 • Working with XML writer.Formatting = Formatting.Indented; doc.WriteTo( writer ); writer.Flush(); m_strOutput += writerString.ToString(); } } } The program runs through two sets of XPath queries against the personnel .xml file.The first set of queries is against XML loaded into an object of type System.Xml.XPath.XPathDocument.The XPathDocument class has been optimized to work with XPath queries. It supports read-only access to the document. An XPathNavigator class object is used to perform queries against an XPathDocument document. Here is the code that instantiates and loads an XPathDocument with XML from a disk file.An XPathNavigtor class object is instantiated to perform XPath queries against the document: XPathDocument doc = new XPathDocument( "personnel.xml" ); XPathNavigator navigator = doc.CreateNavigator(); The Select method of the XPathNavigator class is used to perform a query against the XML document. It takes an XPath statement as an argument.The fol- lowing query returns all of the <Wage> elements in the XML document: XPathNodeIterator iterator = navigator.Select( "descendant::Employee/Wage" ); while ( iterator.MoveNext() ) { m_strOutput += iterator.Current.Name + ": "; m_strOutput += iterator.Current.Value + "\r\n"; } The select statement takes an XPath expression as an argument and returns an XPathNodeIterator object, which is used to traverse the node list returned.The Current property of XPathNodeIterator points to the current position in the node list returned form the Select method call.The position is undefined until the first www.syngress.com Figure 9.13 Continued Working with XML • Chapter 9 477 call to the MoveNext method. As each <Wage> element is encountered in the returned node list, the element tag and value are saved for later display in the listbox on-screen.The Name property of Current returns the element tag and the Value property of Current returns the text contained within the <Wage> element. The second query against the XPathDocument returns all the employees in the Seattle office and displays their names. Here is the code to accomplish this: www.syngress.com XPath Expressions A brief explanation of XPath statements is in order. XPath expressions use what is termed a location path, which is made up of one or more location steps that are separated by a “/” or by a “//”. The “/” character indicates an absolute path, and the “//” characters indicate a relative path from the current node. A location step contains an axis and a node test, and it may contain predicates. The axis indicates the direction of the query from the current node. Examples are child, ancestor, and descendent. The node test is either the name of a node in the document, the wildcard character(*), or one of several node tests such as node() and text(). The predicate is used to filter the node test to pinpoint a spe- cific set of nodes. A predicate is contained within brackets. Here are two examples of XPath expressions: ■ In the XPath expression descendent::Employee/Wage, descendent indicates the axis and Employee/Wage indicates the node test. There is no predicate in this case. The expres- sion returns the Employee/Wage descendents of the current node. ■ In the XPath expression “//Employee[Location/Zip=’98103’], the “//” indicates the axis, Employee indicates the node test and [Location/Zip=’98103’] indicates the predicate. The expression returns the Employee elements with a Location/Zip element whose value is “98103”. These are relatively simple examples. You can combine extremely complex combinations of axes, node tests, and predicates to create extremely powerful queries against XML documents using XPath. Developing & Deploying… 478 Chapter 9 • Working with XML iterator = navigator.Select( "//Employee[Location/Zip='98103']" ); while ( iterator.MoveNext() ) { XPathNavigator nav2 = iterator.Current; nav2.MoveToFirstChild(); m_strOutput += nav2.Value; // First name nav2.MoveToNext(); m_strOutput += ". " + nav2.Value; // Middle init nav2.MoveToNext(); m_strOutput += " " + nav2.Value + "\r\n"; // Last name } The only real difference with this query is that you need to use a second instance of XPathNavigator. Each node in the node list is an <Employee> ele- ment.The second XPathNavigator object is needed so that you can maintain your position in the node list of <Employee> elements. The last query against the XPathDocument object does a summary query. It returns a result, not a node list. Here is the code, which calculates the average salary of all salaried employees: Int32 nAverage = (Int32)(Double)navigator.Evaluate( "sum(//Employee[Salaried='true']/Wage) div count(//Employee[Salaried='true'])" ); When performing summary queries, the Evaluate method is used instead of the Select method. It also takes an XPath expression as an argument.You can see from this example that the XPath expressions can get quite complex. The second set of queries is done against an XmlDocument object. As we men- tioned earlier, an XPathDocument is read-only. So, if you want to use XPath directly against an XML document and update the document, you will need to use an XmlDocument object. Here is the relevant code from the sample: XmlDocument doc = new XmlDocument(); doc.Load( "personnel.xml" ); // Get a list of the Active element nodes for each employee www.syngress.com Working with XML • Chapter 9 479 // in Portland XmlNodeList nodeList = doc.SelectNodes( "//Employee[Location/Zip='97206']/Active"); foreach ( XmlNode node in nodeList ) { // Mark each Portland employee as inactive node.InnerText = "false"; } This example simulates shutting down the Portland office.The <Active> element is set to false for all employees in the Portland office. First, a new XmlDocument object is instantiated and then loaded using the Load method. Next, the XPath query against the document is executed using the SelectNodes method of the System.Xml.Node class. It takes an XPath expression as an argument and returns an XmlNodeList object. In this case, it is a node list containing each <Active> element for each employee in the Portland office.The node list is tra- versed using the foreach statement, and the text value associated with the <Active> element is set to false. Assigning the string “false” to the InnerText prop- erty accomplishes this. Working with XSL The previous section shows how XPath is used as a general query tool. In this sec- tion, you will see XSLT used to transform XML documents to a different format. XSL stylesheets will use XPath expressions to select node lists for transformation. Our sample simulates a real-world scenario.The scenario is that the human resources division of a company named EntegraTech maintains personnel data in an XML file named personnel.xml. Another division of the company maintains a Web site that includes some reports based on personnel information.The Web site uses XSL stylesheets to build HTML Web pages from personnel information contained in XML files. Unfortunately, the Web site stylesheets expect the XML to be in a different format than the format in the personnel.xml file supplied by the HR department.The sample code transforms the XML into the format that the Web site stylesheets expect and then builds one of the HTML reports. XSL stylesheets are used both to transform the XML and to create the HTML. The sample requires the files personnel.xml, salariedpersonnel.xsl, and salariedreport.xsl to be in the same directory the sample is run from.You can find www.syngress.com [...]... the project was a VB.NET project, or aspx.cs, ascx.cs, asmx.cs, and asax.cs respectively if the project was a C# project Figure 10.1 Overview of ASP.NET Architecture Web Client Web Client Web Client ASP.NET Appllication NET Framework IIS NT/2000 Additional Resources Data ASP.NET Server Controls You can add three main sets of controls to your Web Form (ASPX page): HTML server controls ,Web server controls,... chapter ASP.NET is a more robust way to bring applications to the Web Gone are the endless lines of “spaghetti code” and with it the ambiguous debugging.With ASP.NET, you will be able to create cross-browser, cross-platform applications that you can port across the Web Introducing the ASP.NET Architecture In the ASP.NET architecture, the NET Framework works with the OS A Web client requests a Web Form... this: doc.InnerXml = myString www.syngress.com Chapter 10 ASP.NET Solutions in this chapter: ■ Introducing the ASP.NET Architecture ■ Working with Web Forms ■ Working with ADO.NET Summary Solutions Fast Track Frequently Asked Questions 495 496 Chapter 10 • ASP.NET Introduction ASP.NET is Microsoft’s upgrade to Active Server Pages (ASP) ASP.NET architecture is very well woven into the NET Framework to... database ,Web Service, COM component, or a component class All of these are delivered through a compiled assembly (DLL) from the Web application, which sits in the bin directory within IIS’s Web root See Figure 10.1 for a conceptual overview of the ASP.NET architecture ASP.NET includes some new file extensions for the different types of pages you can create in your solutions.The new extensions allow ASP.NET... write ASP.NET pages in any of the managed languages, and the code is compiled to give high performance This chapter acquaints you with writing Web Forms and database-driven Web applications.You will see how you can leverage the use of XML data in the NET Framework within ASP.NET applications, through “real world” examples (a shopping cart and a message board).We also explain how to e-mail from ASP.NET,... for cross browser compliance .Web server controls inherit the System .Web. UI Control namespace, which predefines their attributes.Table 10.2 shows a list of Web server controls.We discuss a number of these in the examples ahead.The following shows a Button Web server control and a Textbox Web server control as they would appear on a Web Form (ASPX page): ... ASP.NET Table 10.3 ASP.NET Validator Controls Validator Control Description CompareValidator Compares a value entered into a Web server control against another set value CustomValidator Can create your own custom validation for specific data RangeValidator Finds the range between two values on a Web server control RegularExpressionValidator Uses regular expressions to validate a value entered into a Web. .. www.syngress.com ASP.NET • Chapter 10 ■ Web server controls A completely new set of controls designed to interact with the NET environment by the additional properties and events included, most notably the ability to do a postback.The tags are XML-based, so they all appear in the same manor as XML elements for ease of use .Web server controls are defaulted to render HTML 3.2 for cross browser compliance .Web server... www.syngress.com ASP.NET • Chapter 10 Working with User Controls If you have some very useful code written in a current Web Form, and you want to reuse that code in another Web Form, you can do that with a user control This is the same as using a server-side include but with all the programming power of an embedded server control.You can access all the properties of the User control within your new Web Form page.This... ): From: To: www.syngress.com ASP.NET • Chapter 10 . Another division of the company maintains a Web site that includes some reports based on personnel information.The Web site uses XSL stylesheets to build HTML Web pages from personnel information contained. 9.16 shows it again for comparison with the format expected by the Web site. Figure 9. 17 shows the format of the XML expected by the Web site. Comparing these two will help in understanding what the. N .72 nd</Address> <City>Seattle</City> <State>WA</State> <Zip>98103</Zip> </Location> </Employee> Figure 9. 17 XML Format Expected by the Web

Ngày đăng: 12/08/2014, 12:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan