<?
xml version="1.0"
?>
<
xsd:schema
xmlns:xsd
="http://www.w3.org/2001/XMLSchema"
>
<!--
Your schema definition goes here
-->
</
xsd:schema
>
<!--
Like XDR schemas, W3C schemas are generally linked to external files that provide the basic definition of what a schema is.
As a result, the W3C-compliant schemas you create will typically begin with a reference to the standard W3C schema definition
(known as the schema of schemas).
The W3C schema definition gives your schema access to basic data types and structures
you'll need to construct schemas to define and validate your XML documents.
This boilerplate provides the same basic function as the initial definition of the XDR schema shown in a previous example,
but it provides a different basic schema type and associates it with the xsd namespace.
This means that you'll often see elements of a W3C schema prefixed with the xsd namespace;
this is done to prevent namespace collisions
between elements defined by the xsd schema definition and elements in your documents with the same name.
-->
Listing 10.32 Example of an XDR Schema
<
Schema
xmlns
="urn:schemas-microsoft-com:xml-data"
xmlns:dt
="urn:schemas-microsoft-com:datatypes"
>
<
ElementType
name
='TITLE'
content
='textOnly'
/>
<
AttributeType
name
='IDType'
dt:type
='integer'
/>
<
ElementType
name
='AUTHOR'
content
='textOnly'>
<attribute type
='IDType'
/>
</
ElementType
>
<
ElementType
name
='BOOK'
content
='mixed'>
<element type
= 'TITLE'
/>
<
element
type
= 'AUTHOR'
/>
</
ElementType
>
</
Schema
>
using
System;
using
System.Xml;
using
System.Xml.XPath;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
C:\\books.xml
"
;
string
friendlyInputMessage
=
"
Please input the xpath that you want to search:
"
;
bool
isNoInput
=
false
;
while
(
!
isNoInput)
{
string
input
=
string
.Empty;
try
{
Console.WriteLine(friendlyInputMessage);
if
((input
=
Console.ReadLine())
!=
string
.Empty)
{
XmlNodeList nodeList
=
QueryXml(xmlPath, input);
string
output
=
string
.Empty;
foreach
(XmlNode node
in
nodeList)
{
output
+=
node.OuterXml;
//
Console.Write(node.OuterXml);
}
Console.WriteLine(output);
}
else
isNoInput
=
true
;
}
catch
(Exception ex)
{
Console.WriteLine(
"
{0} Your input is '{1}'
"
,ex.Message,input);
}
}
}
private
static
XmlNodeList QueryXml(
string
xmlPath,
string
queryPath)
{
/*
* XPath Query Expression: /BOOKS/BOOK/AUTHOR[@id = "107"]/parent::*
* In this case, the @ symbol indicates that id is an attribute instead of the name of a note.
* Note that this expression will retrieve multiple instances of a given author in a case
* where a document contains multiple books with the same author.
* The parent::* clause added to the end of the XPath expression in this example
* tells the query to retrieve the data as well as the parent node.
*
* You can combine multiple query criteria using AND and OR logic.
* BOOKS/BOOK/AUTHOR[@location="Seattle" or @location="San Francisco"]
*
* XPath Query Expression: /BOOKS/BOOK/AUTHOR[@location != "Seattle"]
* XPath Query Expression: /BOOKS/BOOK/AUTHOR[@id > 105]
*
* In addition to querying on attributes, you can also query on the text contained in nodes.
* XPath Query Expression: /BOOKS/BOOK/TITLE[. = "How to Pluck a Purdue Chicken"]/parent::*
* The dot (.) operator is XPath-ese for "right here."
*
* There is another way to retrieve all the books
* whose title matches a given text string without using the parent::* expression.
* You can instead include the parameter element in square brackets.
* retrieving all the TITLE nodes (and their parent BOOK nodes) given a specific title you specify.
* XPath Query Expression: /BOOKS/BOOK[TITLE = 'How to Pluck a Purdue Chicken']
*
*/
XmlDocument xd
=
new
XmlDocument();
xd.Load(xmlPath);
/*
* If you were interested in retrieving only one instance of the AUTHOR node,
* you could use the XmlNodeReader's SelectSingle method (rather than Select method).
* This ensures that you retrieve only the first instance of the data.
*/
return
xd.SelectNodes(queryPath);
}
}
}
using
System;
using
System.Xml;
using
System.Xml.XPath;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
C:\\books.xml
"
;
const
string
newXmlPath
=
"
C:\\new_books.xml
"
;
XmlDocument xd
=
new
XmlDocument();
xd.Load(xmlPath);
XmlNode root
=
xd.DocumentElement;
//
Insert book element
/*
* To insert a node, you use the InsertAfter or InsertBefore methods of the XmlNode object.
* This method takes two parameters: the new child node to insert and a reference to an existing node.
* The location of the existing node determines where the new node should go.
*/
XmlElement eleBook
=
xd.CreateElement(
"
Book
"
);
root.InsertAfter(eleBook,root.FirstChild);
//
Insert TITLE element beneath the book
XmlElement eleTitle
=
xd.CreateElement(
"
TITLE
"
);
eleTitle.InnerText
=
"
My Title
"
;
eleBook.AppendChild(eleTitle);
/*
* You can see from the previous two listings that
* changes to a document using the DOM change only the in-memory representation of the object,
* not the way the document is stored on disk.
* If you want to persist the changes to disk,
* you must use the Save method of the XmlDocument object.
* Therefore, to save the changes you made to the document,
* you execute the Save method of the XmlDocument object that created the document.
*/
xd.Save(newXmlPath);
Console.Read();
}
}
}
using
System;
using
System.Xml;
using
System.Xml.XPath;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
//
To begin performing XPath queries, you start by creating an XPathDocument object.
//
This object is analogous to the XmlDocument object.
XPathDocument xpd
=
new
XPathDocument(xmlPath);
/*
* After you've created an XPathDocument object,
* you use the object's CreateNavigator method to create an instance of the XPathNavigator object.
* The XPathNavigator object is responsible for performing the actual XPath query of the document;
* it returns an iterator (an instance of System.Xml.XPath.XPathNodeIterator) that
* you can use to access each of the elements returned by the query.
*/
XPathNavigator nav
=
xpd.CreateNavigator();
/*
* The Select method of the XPathNavigator object enables you to filter and retrieve subsets of XML data from any XML document.
* You do this by constructing an XPath expression and passing the expression to the Select method of the XPathNavigator object.
* An XPath expression is a compact way of querying an XML document without going to the trouble of parsing the whole thing first.
* Using XPath, it's possible to retrieve very useful subsets of information from an XML document, often with only a single line of code.
*
* The product of this operation is a selection,
* a subset of XML nodes that can then be manipulated independently of the main document.
* You can traverse the selection using the XPathNodeIterator object
* returned from your call to the Select method of the XPathNavigator object.
* After you have an iterator, you can retrieve and display the data from the selected nodes.
*/
XPathNodeIterator iterator
=
nav.Select(
"
note/from
"
);
while
(iterator.MoveNext())
{
/*
* When you retrieve data in this manner, you may need to further manipulate each node.
* You can do this by using the Current property of the XPathNodeIterator object.
* This property, an instance of an XPathNavigator object,
* contains a rich set of properties and methods for manipulating properties of an XML node retrieved by an XPath query.
*/
Console.WriteLine(
"
The mail is from
"
+
iterator.Current);
Console.WriteLine(
"
The property value is
"
+
iterator.Current.Value);
}
Console.Read();
}
}
}
using
System;
using
System.Xml;
using
System.Xml.XPath;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
//
To begin performing XPath queries, you start by creating an XPathDocument object.
//
This object is analogous to the XmlDocument object.
XPathDocument xpd
=
new
XPathDocument(xmlPath);
/*
* After you've created an XPathDocument object,
* you use the object's CreateNavigator method to create an instance of the XPathNavigator object.
* The XPathNavigator object is responsible for performing the actual XPath query of the document;
* it returns an iterator (an instance of System.Xml.XPath.XPathNodeIterator) that
* you can use to access each of the elements returned by the query.
*/
XPathNavigator nav
=
xpd.CreateNavigator();
/*
* The Select method of the XPathNavigator object enables you to filter and retrieve subsets of XML data from any XML document.
* You do this by constructing an XPath expression and passing the expression to the Select method of the XPathNavigator object.
* An XPath expression is a compact way of querying an XML document without going to the trouble of parsing the whole thing first.
* Using XPath, it's possible to retrieve very useful subsets of information from an XML document, often with only a single line of code.
*
* The product of this operation is a selection,
* a subset of XML nodes that can then be manipulated independently of the main document.
* You can traverse the selection using the XPathNodeIterator object
* returned from your call to the Select method of the XPathNavigator object.
* After you have an iterator, you can retrieve and display the data from the selected nodes.
*/
XPathNodeIterator iterator
=
nav.Select(
"
note/from
"
);
while (iterator.MoveNext())
{
/*
* When you retrieve data in this manner, you may need to further manipulate each node.
* You can do this by using the Current property of the XPathNodeIterator object.
* This property, an instance of an XPathNavigator object,
* contains a rich set of properties and methods for manipulating properties of an XML node retrieved by an XPath query.
*/
Console.WriteLine("The mail is from " + iterator.Current);
Console.WriteLine("The property value is " + iterator.Current.Value);
}
Console.Read();
}
}
}
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Xml;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
XmlDocument xd
=
new
XmlDocument();
xd.Load(xmlPath);
XmlNodeReader reader
=
new
XmlNodeReader(xd);
/*
* This is another example of how repeated calls to the Read method control the looping structure
* the same way you use the Read method of the XmlTextReader object (discussed earlier in this chapter).
* Because Read returns true when it successfully navigates to a new element and
* false when no more data is left to traverse to,
* it's easy to set up a while loop that displays all the data in the document.
*/
while
(reader.Read())
Console.WriteLine(reader.Name
+
"
-
"
+
reader.Value );
Console.Read();
}
}
}
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Xml;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
/*
The XML file content to create:
<?xml version="1.0" encoding="utf-8"?>
<BOOK CaseSensitive="true">
<TITLE >C# Developer's Guide</TITLE>
</BOOK>
*/
const
string
xmlPath
=
"
c:\\book.xml
"
;
XmlTextWriter writer
=
new
XmlTextWriter(xmlPath, Encoding.UTF8);
/*
* Normally we don't include exception-handling code in our brief code examples
* (mainly because we're lazy sods,
* but also because they sometimes detract from the point of the code example).
* But in this case, we've included a handler to emphasize that it's important to handle exceptions in code
* that creates or modifies files.
* If you fail to include an exception handler in file-handling code,
* it's easy to make a mistake that prevents a file from being closed properly, for example, which is a bad thing.
*/
try
{
/*
* We then call the WriteStartDocument method to begin working with the document.
* This has the side effect of sending an XML declaration to the document.
* Calling WriteStartDocument is required when using the XmlTextWriter,
* even though XML itself does not require that a declaration entity be present in a document.
*/
writer.WriteStartDocument();
//
Next we create the root node of the document with a call to the WriteStartElement method.
writer.WriteStartElement(
"
BOOK
"
);
//
To create attributes associated with nodes, use the XmlTextWriter object's WriteAttributeString method.
writer.WriteAttributeString(
"
CaseSensitive
"
,
"
true
"
);
//
Next, we insert a node underneath the root node with a call to WriteElementString.
writer.WriteElementString(
"
TITLE
"
,
"
C# Developer's Guide
"
);
/*
* When we're done with the document,
* we call the WriteEndDocument method to close the root node
* and then call the Flush and Close methods to finish the process of committing the file to disk.
*/
//
write the end mark of the root element.
writer.WriteEndElement();
writer.WriteEndDocument();
}
catch
(Exception ex)
{
Console.Write(
"
Exception:{0}
"
, ex.Message);
}
finally
{
writer.Flush();
writer.Close();
Console.Read();
}
}
}
}
//Extracting the Message Sender Using the
XmlTextReader Object
using
System;
using
System.Text;
using
System.Xml;
namespace
LearningXml
{
class
Program
{
static
void
Main(
string
[] args)
{
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
XmlTextReader reader
=
new
XmlTextReader(xmlPath);
bool
isFromNode
=
false
;
while
(reader.Read())
{
switch
(reader.NodeType)
{
case
XmlNodeType.Element:
if
(reader.Name
==
"
from
"
)
isFromNode
=
true
;
break
;
case
XmlNodeType.Text:
if
(isFromNode)
{
Console.WriteLine(
"
The message is from {0}
"
,reader.ReadString());
Console.Read();
return
;
}
break
;
}
}
}
}
}
1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
using
System.Xml;
5
namespace
LearningXml
6
{
7
class
Program
8
{
9
static
void
Main(
string
[] args)
10
{
11
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
12
XmlDocument xml
=
new
XmlDocument();
13
xml.Load(xmlPath);
14
XmlNode node
=
xml.LastChild;
15
foreach
(XmlNode nd
in
node.ChildNodes)
16
{
17
if
(nd.Name
==
"
to
"
)
18
Console.WriteLine(
"
The message is sent to '{0}'.
"
,nd.InnerText);
19
}
20
Console.Read();
21
}
22
}
23
}
24
//The full content of http://www.w3schools.com/xml/note.xml
1
<?
xml version="1.0" encoding="ISO-8859-1"
?>
2
<!--
Edited with XML Spy v2007 (http://www.altova.com)
-->
3
<
note
>
4
<
to
>
Tove
</
to
>
5
<
from
>
Jani
</
from
>
6
<
heading
>
Reminder
</
heading
>
7
<
body
>
Don't forget me this weekend!
</
body
>
8
</
note
>
// Loading an XML
File That Resides on a Web Server
1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
using
System.Xml;
5
namespace
LearningXml
6
{
7
class
Program
8
{
9
static
void
Main(
string
[] args)
10
{
11
const
string
xmlPath
=
"
http://www.w3schools.com/xml/note.xml
"
;
12
XmlDocument xml
=
new
XmlDocument();
13
xml.Load(xmlPath);
14
Console.Write(xml.OuterXml);
15
Console.Read();
16
}
17
}
18
}
19
<!--Loading a Local XML File Using the XmlDocument's .Load() Method-->
<%
@Page language
=
"
C#
"
debug
=
"
true
"
%>
<%
@ Import Namespace
=
"
System.Xml
"
%>
<
SCRIPT
runat
='server'
>
void
Page_Load(Object Sender,EventArgs e)
{
XmlDocument xd
=
new
XmlDocument();
xd.Load(Server.MapPath(
"
books.xml
"
));
Response.Write (xd.OuterXml);
xd
=
null
;
}
</
SCRIPT
>
<!-- Loading an XML
File That Resides on a Web Server
-->
<%
@Page language
=
"
C#
"
debug
=
"
true
"
%>
<%
@ Import Namespace
=
"
System.Xml
"
%>
<
SCRIPT
runat
='server'
>
void
Page_Load(Object Sender,EventArgs e)
{
XmlDocument xd
=
new
XmlDocument();
xd.Load(
"
http://www.myserver.com/books.xml
"
);
Response.Write (xd.OuterXml);
xd
=
null
;
}
</
SCRIPT
>
//Loading a Local XML File Using
the XmlDocument's
.Load() Method
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Xml;
5
namespace
LearningXml
6
{
7
class
Program
8
{
9
static
void Main(
string
[] args)
10
{
11
const
string
xmlPath
=
"
c:\\books.xml
"
;
12
XmlDocument xml
=
new
XmlDocument();
13
xml.Load(xmlPath);
14
Console.Write(xml.OuterXml);
15
Console.Read();
16
}
17
}
18
}
19
<
% @Page language
=
"
C#
"
debug
=
"
true
"
%
>
<
%@ Import
Namespace
=
"
System.Xml
"
%
>
<
SCRIPT runat
=
'
server'>
void Page_Load(
Object
Sender,EventArgs e)
{
XmlDocument xd
=
new
XmlDocument();
xd.Load(Server.MapPath(
"
books.xml
"
));
Response.Write (xd.OuterXml);
xd
=
null;
}
</
SCRIPT
>
<!--
The Full Contents of the books.xml Document Example
-->
<
BOOKS
>
<
BOOK
>
<
TITLE
>
C# Developer's Guide To ASP.NET, XML and ADO.NET
</
TITLE
>
<
AUTHOR
id
='101'
location
='San
Francisco'
>
Jeffrey P. McManus
</
AUTHOR
>
<
AUTHOR
id
='107'
location
='Seattle'>Chris
Kinsman</AUTHOR
>
</
BOOK
>
</
BOOKS
>
1
<?
xml version="1.0"
?>
2
<
ORDERS
>
3
<
ORDER
id
="33849"
custid
="406"
>
4
<
DATETIME
>
1/4/2000 9:32 AM
</
DATETIME
>
5
<
TOTALAMOUNT
/>
6
</
ORDER
>
7
</
ORDERS
>
1
<?
xml version=" 1.0"
?>
2
<
ORDERS
>
3
<
ORDER
id
="33849"
>
4
<
NAME
>
<![CDATA[
Jones & Williams Certified Public Accountants
]]>
</
NAME
>
5
<
DATETIME
>
1/4/2000 9:32 AM
</
DATETIME
>
6
<
TOTALAMOUNT
>
3456.92
</
TOTALAMOUNT
>
7
</
ORDER
>
8
</
ORDERS
>
<![CDATA[]]>
1
<?
xml version="1.0"
?>
2
<
ORDERS
>
3
<
ORDER
id
="33849"
>
4
<
NAME
>
Jones
&
Williams Certified Public Accountants
</
NAME
>
5
<
DATETIME
>
1/4/2000 9:32 AM
</
DATETIME
>
6
<
TOTALAMOUNT
>
3456.92
</
TOTALAMOUNT
>
7
</
ORDER
>
8
</
ORDERS
>
d
<?
xml version="1.0"
?>
<?
xml version="1.0"
?>
<
ORDERS
>
</
ORDERS
>
1
<?
xml version="1.0"
?>
2
<
ORDERS
>
3
<
ORDER
>
4
<
DATETIME
>
1/4/2000 9:32 AM
</
DATETIME
>
5
<
ID
>
33849
</
ID
>
6
<
CUSTOMER
>
Steve Farben
</
CUSTOMER
>
7
<
TOTALAMOUNT
>
3456.92
</
TOTALAMOUNT
>
8
</
ORDER
>
9
</
ORDERS
>
1
<?
xml version="1.0"
?>
2
<
ORDERS
>
3
<
ORDER
id
="33849"
custid
="406"
>
4
<
DATETIME
>
1/4/2000 9:32 AM
</
DATETIME
>
5
<
TOTALAMOUNT
>
3456.92
</
TOTALAMOUNT
>
6
</
ORDER
>
7
</
ORDERS
>