SlideShare ist ein Scribd-Unternehmen logo
1 von 22
• 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
XML is an all-purpose way to identify any type of data using
elements. These elements use the same sort of format found in an
HTML file, but while HTML elements indicate formatting, XML
elements 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.
<?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>
Attributes add extra information to an element. Instead of putting
information 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>
.NET provides a rich set of classes for XML manipulation in
several namespaces that start with System.Xml
The classes here allow you to read and write XML
files, manipulate XML data in memory, and even validate
XML 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
One of the simplest ways to create or read any XML
document is to use the basic XmlTextWriter and
XmlTextReader classes. These classes work like their
StreamWriter and StreamReader relatives, except that they
write and read XML documents instead of ordinary text files.

Reading the XML document in your code is just as easy with
the corresponding XmlTextReader class.
The XmlTextReader moves through your document from top
to bottom, one node at a time. You call the Read() method to
move to the next node.

This method returns true if there are more nodes to read or
false once it has read the final node. The current node is
provided through the properties of the XmlTextReader
class, such as NodeType and Name.
An XML document is a collection of elements structured
according to the rules of XML. An XML document can be
stored in virtually any way you want—it can be placed in a
file, in a field, or in a database, or it can simply exist in
memory.

You can find the XDocument and all related classes in the
System.Xml.Linq namespace.

When you use the XDocument class, your XML document
is created as a series of linked .NET objects in memory.
To start building a next XML document, you need to
create the XDocument, XElement, and XAttribute objects
that comprise it. All these classes have useful
constructors that allow you to create and initialize them in
one 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>
You can extend this technique to create an entire XML
document, complete with elements, text content, attributes

XDocument 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);
The XDocument makes it easy to read and navigate XML
content. You can use the static XDocument.Load()
method to read XML documents from a file, URI, or
stream, and you can use the static XDocument.Parse()
method to load XML content from a string.

Once you have the XDocument with your content in
memory, you can dig into the tree of nodes using a few
key properties and methods of the XElement and
XDocument class.
XDocument doc = XDocument.Load(file);
// Loop through all the nodes, and create the list of Product
objects .
List<Product> products = new List<Product>();
foreach (XElement element in
doc.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();
To search an XDocument, all you need to do is use
the Descendants() or DescendantNodes() method.
Both methods allow you to search through the entire
document 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 />";
}
XML has a rich set of supporting standards one of
the most useful in this family of standards is XML Schema.

XML Schema defines the rules to which a specific XML
document should conform, such as the allowable elements
and attributes, the order of elements, and the data type of
each element. You define these requirements in an XML
Schema document (XSD).

If you want to open your application to other
programmers or allow it to interoperate with other
applications, you should create an XSD.

 XML allows you to create a custom language for storing
data, and XSD allows you to define the syntax of the
language you create.
Namespace is used to uniquely identify all related elements.
For example, you could tell the difference between your
SuperProProductList standard and another organization’s
product catalog because the two XML languages would use
different namespaces.

Namespaces are particularly useful in compound documents,
which contain separate sections, each with a different type of
XML. In this scenario, namespaces ensure that an element in
one namespace can’t be confused with an element in another
namespace, even if it has the same element name.

Namespaces are also useful for applications that support
different types of XML documents.

By examining the namespace, your code can determine what
type of XML document it’s working with and can then process it
accordingly.
Most XML namespaces use Universal Resource Identifiers (URIs).
Typically, these URIs look like a web page URL.

For example, http://www.mycompany.com/mystandard is a typical
name for a namespace. Though the namespace looks like it points
to a valid location on the Web, this isn’t required (and shouldn’t be
assumed).

The reason that URIs are used for XML namespaces is because
they are more likely to be unique.

Typically, if you create a new XML markup, you’ll use a URI that
points to a domain or website you control. That way, you can be
sure that no one else is likely to use that URI. For example, the
namespace http://www.SuperProProducts.com/SuperProProductList
is much more likely to be unique than just SuperProProductList if
you own the domain www.SuperProProducts.com.
An XSD, or schema, defines what elements and attributes a document
should contain and the way these nodes are organized (the structure)
<?xml version="1.0"?> <xs:schema targetNamespace =
http://www.SuperProProducts.com/SuperProProductList xmlns:xs=
http://www.w3.org/2001/XMLSchema 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>
Using an XmlReader that has validation features built in. The first step
when performing validation is to import the System.Xml.Schema
namespace, which contains types such as XmlSchema and
XmlSchemaCollection:
You must perform two steps to create the validating reader.
First, you create an XmlReaderSettings object that specifically indicates
you want to perform validation. You do this by setting the ValidationType
property and loading your XSD schema file into the Schemas collection
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
string schemaFile = Path.Combine(Request.PhysicalApplicationPath,
@"App_DataSuperProProductList.xsd");
settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProd
uctList", schemaFile);
Second, you need to create the validating reader using the static
XmlReader.Create() method.
FileStream fs = new FileStream(file, FileMode.Open);
XmlReader r = XmlReader.Create(fs, settings);
Another standard associated with XML is XSL Transformations (XSLT).
XSLT allows you to create style sheets that can extract a portion of a
large XML document or transform an XML document into another
type 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. All
you need to understand is how to create an XslCompiledTransform object
(found in the System.Xml.Xsl namespace). You use its Load() method to
specify a style sheet and its Transform() method to output the result to a
file 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);
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform 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>
The XslCompiledTransform object just converts XML files—it doesn’t
provide any way to insert the output into your web page.

ASP.NET includes an Xml web control that fills the gap and can display
XML content. You can specify the XML content for this control in
several ways.

For example, you can assign a string containing the XML content to the
DocumentContent property, or you can specify a string that refers to an
XML file using the DocumentSource property.

// Display the information from an XML file in the Xml control.
XmlProducts.DocumentSource =
Path.Combine(Request.PhysicalApplicationPath, @"App_DataSuperP
roProductList.xml");

// Specify a XSLT file.
XmlProducts.TransformSource =
Path.Combine(Request.PhysicalApplicationPath,
@"App_DataSuperProProductList.xsl");

Weitere ähnliche Inhalte

Was ist angesagt? (20)

XML/XSLT
XML/XSLTXML/XSLT
XML/XSLT
 
Xml part3
Xml part3Xml part3
Xml part3
 
Xml basics
Xml basicsXml basics
Xml basics
 
Xsd examples
Xsd examplesXsd examples
Xsd examples
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
Xml part2
Xml part2Xml part2
Xml part2
 
Basics of XML
Basics of XMLBasics of XML
Basics of XML
 
Xml schema
Xml schemaXml schema
Xml schema
 
Xsd
XsdXsd
Xsd
 
Learning XSLT
Learning XSLTLearning XSLT
Learning XSLT
 
Xml basics for beginning
Xml basics for beginningXml basics for beginning
Xml basics for beginning
 
Xml part1
Xml part1  Xml part1
Xml part1
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
XSLT
XSLTXSLT
XSLT
 
XML Schema
XML SchemaXML Schema
XML Schema
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
Xml part5
Xml part5Xml part5
Xml part5
 
XSLT
XSLTXSLT
XSLT
 
Displaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSLDisplaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSL
 

Andere mochten auch (13)

Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Chapter 26
Chapter 26Chapter 26
Chapter 26
 
Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
07 asp.net session10
07 asp.net session1007 asp.net session10
07 asp.net session10
 
Assignment
AssignmentAssignment
Assignment
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NET
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 

Ähnlich wie Chapter 18 (20)

Oracle soa xml faq
Oracle soa xml faqOracle soa xml faq
Oracle soa xml faq
 
XML1.pptx
XML1.pptxXML1.pptx
XML1.pptx
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Xml writers
Xml writersXml writers
Xml writers
 
Xml
XmlXml
Xml
 
Xml iet 2015
Xml iet 2015Xml iet 2015
Xml iet 2015
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
 
CTDA Workshop on XML and MODS
CTDA Workshop on XML and MODSCTDA Workshop on XML and MODS
CTDA Workshop on XML and MODS
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
Xml viva questions
Xml viva questionsXml viva questions
Xml viva questions
 
chapter 4 web authoring unit 4 xml.pptx
chapter 4 web authoring  unit 4 xml.pptxchapter 4 web authoring  unit 4 xml.pptx
chapter 4 web authoring unit 4 xml.pptx
 
Xml intro1
Xml intro1Xml intro1
Xml intro1
 
XML
XMLXML
XML
 
Xml andweb services
Xml andweb services Xml andweb services
Xml andweb services
 
Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12
 
XML Schema.pptx
XML Schema.pptxXML Schema.pptx
XML Schema.pptx
 
xml.pptx
xml.pptxxml.pptx
xml.pptx
 
The xml
The xmlThe xml
The xml
 

Mehr von application developer (20)

Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Week 1 Assignment Q2 Solution
Week 1 Assignment Q2 SolutionWeek 1 Assignment Q2 Solution
Week 1 Assignment Q2 Solution
 
Week 1 assignment q2
Week 1 assignment q2Week 1 assignment q2
Week 1 assignment q2
 
Week 1 Assignment Q1 Solution
Week 1 Assignment Q1 SolutionWeek 1 Assignment Q1 Solution
Week 1 Assignment Q1 Solution
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Week 1 assignment
Week 1 assignmentWeek 1 assignment
Week 1 assignment
 
C# question answers
C# question answersC# question answers
C# question answers
 
Chapter 3 part2
Chapter 3  part2Chapter 3  part2
Chapter 3 part2
 

Kürzlich hochgeladen

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Kürzlich hochgeladen (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Chapter 18

  • 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. XML is an all-purpose way to identify any type of data using elements. These elements use the same sort of format found in an HTML file, but while HTML elements indicate formatting, XML elements 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.
  • 4. Attributes add extra information to an element. Instead of putting information 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. .NET provides a rich set of classes for XML manipulation in several namespaces that start with System.Xml The classes here allow you to read and write XML files, manipulate XML data in memory, and even validate XML 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. One of the simplest ways to create or read any XML document is to use the basic XmlTextWriter and XmlTextReader classes. These classes work like their StreamWriter and StreamReader relatives, except that they write and read XML documents instead of ordinary text files. Reading the XML document in your code is just as easy with the corresponding XmlTextReader class. The XmlTextReader moves through your document from top to bottom, one node at a time. You call the Read() method to move to the next node. This method returns true if there are more nodes to read or false once it has read the final node. The current node is provided through the properties of the XmlTextReader class, such as NodeType and Name.
  • 7. An XML document is a collection of elements structured according to the rules of XML. An XML document can be stored in virtually any way you want—it can be placed in a file, in a field, or in a database, or it can simply exist in memory. You can find the XDocument and all related classes in the System.Xml.Linq namespace. When you use the XDocument class, your XML document is created as a series of linked .NET objects in memory.
  • 8.
  • 9. To start building a next XML document, you need to create the XDocument, XElement, and XAttribute objects that comprise it. All these classes have useful constructors that allow you to create and initialize them in one 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>
  • 10. You can extend this technique to create an entire XML document, complete with elements, text content, attributes XDocument 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);
  • 11. The XDocument makes it easy to read and navigate XML content. You can use the static XDocument.Load() method to read XML documents from a file, URI, or stream, and you can use the static XDocument.Parse() method to load XML content from a string. Once you have the XDocument with your content in memory, you can dig into the tree of nodes using a few key properties and methods of the XElement and XDocument class.
  • 12.
  • 13. XDocument doc = XDocument.Load(file); // Loop through all the nodes, and create the list of Product objects . List<Product> products = new List<Product>(); foreach (XElement element in doc.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();
  • 14. To search an XDocument, all you need to do is use the Descendants() or DescendantNodes() method. Both methods allow you to search through the entire document 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 />"; }
  • 15. XML has a rich set of supporting standards one of the most useful in this family of standards is XML Schema. XML Schema defines the rules to which a specific XML document should conform, such as the allowable elements and attributes, the order of elements, and the data type of each element. You define these requirements in an XML Schema document (XSD). If you want to open your application to other programmers or allow it to interoperate with other applications, you should create an XSD. XML allows you to create a custom language for storing data, and XSD allows you to define the syntax of the language you create.
  • 16. Namespace is used to uniquely identify all related elements. For example, you could tell the difference between your SuperProProductList standard and another organization’s product catalog because the two XML languages would use different namespaces. Namespaces are particularly useful in compound documents, which contain separate sections, each with a different type of XML. In this scenario, namespaces ensure that an element in one namespace can’t be confused with an element in another namespace, even if it has the same element name. Namespaces are also useful for applications that support different types of XML documents. By examining the namespace, your code can determine what type of XML document it’s working with and can then process it accordingly.
  • 17. Most XML namespaces use Universal Resource Identifiers (URIs). Typically, these URIs look like a web page URL. For example, http://www.mycompany.com/mystandard is a typical name for a namespace. Though the namespace looks like it points to a valid location on the Web, this isn’t required (and shouldn’t be assumed). The reason that URIs are used for XML namespaces is because they are more likely to be unique. Typically, if you create a new XML markup, you’ll use a URI that points to a domain or website you control. That way, you can be sure that no one else is likely to use that URI. For example, the namespace http://www.SuperProProducts.com/SuperProProductList is much more likely to be unique than just SuperProProductList if you own the domain www.SuperProProducts.com.
  • 18. An XSD, or schema, defines what elements and attributes a document should contain and the way these nodes are organized (the structure) <?xml version="1.0"?> <xs:schema targetNamespace = http://www.SuperProProducts.com/SuperProProductList xmlns:xs= http://www.w3.org/2001/XMLSchema 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>
  • 19. Using an XmlReader that has validation features built in. The first step when performing validation is to import the System.Xml.Schema namespace, which contains types such as XmlSchema and XmlSchemaCollection: You must perform two steps to create the validating reader. First, you create an XmlReaderSettings object that specifically indicates you want to perform validation. You do this by setting the ValidationType property and loading your XSD schema file into the Schemas collection XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; string schemaFile = Path.Combine(Request.PhysicalApplicationPath, @"App_DataSuperProProductList.xsd"); settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProd uctList", schemaFile); Second, you need to create the validating reader using the static XmlReader.Create() method. FileStream fs = new FileStream(file, FileMode.Open); XmlReader r = XmlReader.Create(fs, settings);
  • 20. Another standard associated with XML is XSL Transformations (XSLT). XSLT allows you to create style sheets that can extract a portion of a large XML document or transform an XML document into another type 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. All you need to understand is how to create an XslCompiledTransform object (found in the System.Xml.Xsl namespace). You use its Load() method to specify a style sheet and its Transform() method to output the result to a file 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);
  • 21. <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform 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>
  • 22. The XslCompiledTransform object just converts XML files—it doesn’t provide any way to insert the output into your web page. ASP.NET includes an Xml web control that fills the gap and can display XML content. You can specify the XML content for this control in several ways. For example, you can assign a string containing the XML content to the DocumentContent property, or you can specify a string that refers to an XML file using the DocumentSource property. // Display the information from an XML file in the Xml control. XmlProducts.DocumentSource = Path.Combine(Request.PhysicalApplicationPath, @"App_DataSuperP roProductList.xml"); // Specify a XSLT file. XmlProducts.TransformSource = Path.Combine(Request.PhysicalApplicationPath, @"App_DataSuperProProductList.xsl");