Successfully reported this slideshow.

Chapter 18


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Chapter 18

  1. 1. • XML Explained• XML Classes• XML TextWriter / TextReader• XML Documents in Memory• XML Namespaces• XML Schema Definition• Validating an XML Document• XML Display and Transforms• The XML Web Control
  2. 2. XML is an all-purpose way to identify any type of data usingelements. These elements use the same sort of format found in anHTML file, but while HTML elements indicate formatting, XMLelements indicate content. XML documents must start with an XML declaration like <?xml version="1.0"?> XML elements are composed of a start tag (like <Name>) and an end tag (like </Name>). Content is placed between the start and end tags. Whitespace between elements is ignored You can use only valid characters in the content for an element. You can’t enter special characters, such as the angle brackets (< >) and the ampersand (&), as content. Instead, you’ll have to use the entity equivalents (such as &lt; and &gt; for angle brackets, and &amp; for the ampersand). XML elements are case sensitive, so <ID> and <id> are completely different elements All elements must be nested in a root element. Every element must be fully enclosed.
  3. 3. <?xml version="1.0"?><SuperProProductList><Product><ID>1</ID><Name>Chair</Name><Price>49.33</Price><Available>True</Available><Status>3</Status></Product><Product><ID>2</ID><Name>Car</Name><Price>43399.55</Price><Available>True</Available><Status>3</Status></Product></SuperProProductList>
  4. 4. Attributes add extra information to an element. Instead of puttinginformation into a subelement, you can use an attribute.<?xml version="1.0"?><SuperProProductList><Product ID="1" Name="Chair"><Price>49.33</Price><Available>True</Available><Status>3</Status></Product><Product ID="2" Name="Car"><Price>43399.55</Price><Available>True</Available><Status>3</Status></Product></SuperProProductList>
  5. 5. .NET provides a rich set of classes for XML manipulation inseveral namespaces that start with System.XmlThe classes here allow you to read and write XMLfiles, manipulate XML data in memory, and even validateXML documents.Following are the options for dealing with XML data:• Reading and writing XML directly, just like you read and write text files using XmlTextWriter and XmlTextReader.• Dealing with XML as a collection of in-memory objects using the XDocument class.• Using the Xml control to transform XML content to displayable HTML using a prebuilt XSLT style sheet
  6. 6. One of the simplest ways to create or read any XMLdocument is to use the basic XmlTextWriter andXmlTextReader classes. These classes work like theirStreamWriter and StreamReader relatives, except that theywrite and read XML documents instead of ordinary text files.Reading the XML document in your code is just as easy withthe corresponding XmlTextReader class.The XmlTextReader moves through your document from topto bottom, one node at a time. You call the Read() method tomove to the next node.This method returns true if there are more nodes to read orfalse once it has read the final node. The current node isprovided through the properties of the XmlTextReaderclass, such as NodeType and Name.
  7. 7. An XML document is a collection of elements structuredaccording to the rules of XML. An XML document can bestored in virtually any way you want—it can be placed in afile, in a field, or in a database, or it can simply exist inmemory.You can find the XDocument and all related classes in theSystem.Xml.Linq namespace.When you use the XDocument class, your XML documentis created as a series of linked .NET objects in memory.
  8. 8. To start building a next XML document, you need tocreate the XDocument, XElement, and XAttribute objectsthat comprise it. All these classes have usefulconstructors that allow you to create and initialize them inone step.XElement element = new XElement("Product",new XElement("ID", 3),new XElement("Name", "Fresh Fruit Basket"),new XElement("Price", "49.99") );Here’s the scrap of XML that this code creates:<Product><ID>3</ID><Name>Fresh Fruit Basket</Name><Price>49.99</Price></Product>
  9. 9. You can extend this technique to create an entire XMLdocument, complete with elements, text content, attributesXDocument doc = new XDocument(new XDeclaration("1.0", null, "yes"),new XComment("Created with the XDocument class."),new XElement("SuperProProductList",new XElement("Product",new XAttribute("ID", 1),new XAttribute("Name", "Chair"),new XElement("Price", "49.33") ),new XElement("Product",new XAttribute("ID", 2),new XAttribute("Name", "Car"),new XElement("Price", "43399.55") ),new XElement("Product", new XAttribute("ID", 3),new XAttribute("Name", "Fresh Fruit Basket"),new XElement("Price", "49.99") ) ) );// Save the document.doc.Save(file);
  10. 10. The XDocument makes it easy to read and navigate XMLcontent. You can use the static XDocument.Load()method to read XML documents from a file, URI, orstream, and you can use the static XDocument.Parse()method to load XML content from a string.Once you have the XDocument with your content inmemory, you can dig into the tree of nodes using a fewkey properties and methods of the XElement andXDocument class.
  11. 11. XDocument doc = XDocument.Load(file);// Loop through all the nodes, and create the list of Productobjects .List<Product> products = new List<Product>();foreach (XElement element indoc.Element("SuperProProductList").Elements("Product")){Product newProduct = new Product();newProduct.ID = (int)element.Attribute("ID");newProduct.Name = (string)element.Attribute("Name");newProduct.Price = (decimal) element.Element("Price");products.Add(newProduct);}// Display the results.gridResults.DataSource = products;gridResults.DataBind();
  12. 12. To search an XDocument, all you need to do is usethe Descendants() or DescendantNodes() method.Both methods allow you to search through the entiredocument tree in one step.XDocument doc = XDocument.Load(file);// Find the matches.var results = doc.Descendants("Price");// Display the results.lblXml.Text = "<b>Found " +results.Count<XElement>().ToString() + " Matches ";lblXml.Text += " for the Price tag: </b><br /><br />";foreach (XElement result in results){lblXml.Text += result.Value + "<br />";}
  13. 13. XML has a rich set of supporting standards one ofthe most useful in this family of standards is XML Schema.XML Schema defines the rules to which a specific XMLdocument should conform, such as the allowable elementsand attributes, the order of elements, and the data type ofeach element. You define these requirements in an XMLSchema document (XSD).If you want to open your application to otherprogrammers or allow it to interoperate with otherapplications, you should create an XSD. XML allows you to create a custom language for storingdata, and XSD allows you to define the syntax of thelanguage you create.
  14. 14. Namespace is used to uniquely identify all related elements.For example, you could tell the difference between yourSuperProProductList standard and another organization’sproduct catalog because the two XML languages would usedifferent namespaces.Namespaces are particularly useful in compound documents,which contain separate sections, each with a different type ofXML. In this scenario, namespaces ensure that an element inone namespace can’t be confused with an element in anothernamespace, even if it has the same element name.Namespaces are also useful for applications that supportdifferent types of XML documents.By examining the namespace, your code can determine whattype of XML document it’s working with and can then process itaccordingly.
  15. 15. Most XML namespaces use Universal Resource Identifiers (URIs).Typically, these URIs look like a web page URL.For example, is a typicalname for a namespace. Though the namespace looks like it pointsto a valid location on the Web, this isn’t required (and shouldn’t beassumed).The reason that URIs are used for XML namespaces is becausethey are more likely to be unique.Typically, if you create a new XML markup, you’ll use a URI thatpoints to a domain or website you control. That way, you can besure that no one else is likely to use that URI. For example, thenamespace much more likely to be unique than just SuperProProductList ifyou own the domain
  16. 16. An XSD, or schema, defines what elements and attributes a documentshould contain and the way these nodes are organized (the structure)<?xml version="1.0"?> <xs:schema targetNamespace = xmlns:xs= elementFormDefault="qualified" ><xs:element name="SuperProProductList"><xs:complexType><xs:sequence maxOccurs="unbounded"><xs:element name="Product"><xs:complexType><xs:sequence><xs:element name="Price" type="xs:double" /></xs:sequence><xs:attribute name="ID" use="required" type="xs:int" /><xs:attribute name="Name" use="required" type="xs:string" /></xs:complexType></xs:element></xs:sequence></xs:complexType></xs:element> </xs:schema>
  17. 17. Using an XmlReader that has validation features built in. The first stepwhen performing validation is to import the System.Xml.Schemanamespace, which contains types such as XmlSchema andXmlSchemaCollection:You must perform two steps to create the validating reader.First, you create an XmlReaderSettings object that specifically indicatesyou want to perform validation. You do this by setting the ValidationTypeproperty and loading your XSD schema file into the Schemas collectionXmlReaderSettings settings = new XmlReaderSettings();settings.ValidationType = ValidationType.Schema;string schemaFile = Path.Combine(Request.PhysicalApplicationPath,@"App_DataSuperProProductList.xsd");settings.Schemas.Add("", schemaFile);Second, you need to create the validating reader using the staticXmlReader.Create() method.FileStream fs = new FileStream(file, FileMode.Open);XmlReader r = XmlReader.Create(fs, settings);
  18. 18. Another standard associated with XML is XSL Transformations (XSLT).XSLT allows you to create style sheets that can extract a portion of alarge XML document or transform an XML document into anothertype of XML or HTML document that can be displayed in a browser.XSLT is easy to use from the point of view of the .NET class library. Allyou need to understand is how to create an XslCompiledTransform object(found in the System.Xml.Xsl namespace). You use its Load() method tospecify a style sheet and its Transform() method to output the result to afile or stream:string xsltFile = Path.Combine(Request.PhysicalApplicationPath,@"App_DataSuperProProductList.xsl");string xmlSourceFile = Path.Combine(Request.PhysicalApplicationPath,@"App_DataSuperProProductList.xml");string xmlResultFile = Path.Combine(Request.PhysicalApplicationPath,@"App_DataTransformedFile.xml");XslCompiledTransform transformer = new XslCompiledTransform();transformer.Load(xsltFile);transformer.Transform(xmlSourceFile, xmlResultFile);
  19. 19. <?xml version="1.0" encoding="UTF-8" ?><xsl:stylesheet xmlns:xsl= version="1.0" ><xsl:template match="SuperProProductList"><html><body><table border="1"><xsl:apply-templates select="Product"/></table></body></html></xsl:template><xsl:template match="Product"><tr><td><xsl:value-of select="@ID"/></td><td><xsl:value-of select="@Name"/></td><td><xsl:value-of select="Price"/></td></tr></xsl:template></xsl:stylesheet>
  20. 20. The XslCompiledTransform object just converts XML files—it doesn’tprovide any way to insert the output into your web page.ASP.NET includes an Xml web control that fills the gap and can displayXML content. You can specify the XML content for this control inseveral ways.For example, you can assign a string containing the XML content to theDocumentContent property, or you can specify a string that refers to anXML file using the DocumentSource property.// Display the information from an XML file in the Xml control.XmlProducts.DocumentSource =Path.Combine(Request.PhysicalApplicationPath, @"App_DataSuperProProductList.xml");// Specify a XSLT file.XmlProducts.TransformSource =Path.Combine(Request.PhysicalApplicationPath,@"App_DataSuperProProductList.xsl");