69
1 XML (6) Extensible Markup Language Acknowledgements and copyrights : these slides are a result of combination of notes and slides with contributions from: Michael Kiffer, Arthur Bernstein, Philip Lewis, Hanspeter Mφssenbφck, Hanspeter Mφssenbφck, Wolfgang Beer, Dietrich Birngruber, Albrecht Wφss, Mark Sapossnek, Bill Andreopoulos, Divakaran Liginlal, Michael Morrison, Anestis Toptsis, Deitel and Associates, Prentice Hall, Addison Wesley, Microsoft AA. They serve for teaching purposes only and only for the students that are registered in CSE4413 and should not be published as a book or in any form of commercial product, unless written permission is obtained from each of the above listed names and/or organizations.

Extensible Markup Language Lecture Notes/xml 06.pdfXmlDocument • Implements W3C XML Document Object Model (DOM) Level 1 and Level 2 specifications •Implements XmlNode – XML elements

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

  • 1

    XML (6)Extensible Markup Language

    Acknowledgements and copyrights: these slides are a result of combination of notes and slides with contributions from: MichaelKiffer, Arthur Bernstein, Philip Lewis, Hanspeter Mφssenbφck,

    Hanspeter Mφssenbφck, Wolfgang Beer, Dietrich Birngruber, Albrecht Wφss, Mark Sapossnek, Bill Andreopoulos, Divakaran Liginlal,

    Michael Morrison, Anestis Toptsis, Deitel and Associates, Prentice Hall, Addison Wesley, Microsoft AA.

    They serve for teaching purposes only and only for the students that are registered in CSE4413 and should not be published as a book or in any

    form of commercial product, unless written permission is obtained from each of the above listed names and/or organizations.

  • 2

    Other conditional tags

  • 3

    Example • • • • • • •
    • This is the Frank Rizzo Contact:: • •
    • • •• •
    • This is the Contact.•
    • • • • • •

    Alternative ways to do the same

    thing.

  • 4

    Result …

  • 5

    Sorting ?xml version="1.0" encoding="UTF-8"?>














    The templates

  • 6

    Result …

    The corresponding XML/HTML file

  • 7

    The XML DOM• XML Document Object Model (DOM)• Provides a programming interface for manipulating XML documents

    in memory• Includes a set of objects and interfaces that represent the content and

    structure of an XML document. Defines the document structure through an object model

    – Tree-view of a document– Nodes, elements and attributes, text elements, etc

    • Enables a program to traverse an XML tree• Allows elements, attributes, etc., to be added/deleted in an XML tree• Allows new XML documents to be created programmatically.• W3C defined the DOM Level 1 and Level 2 Core

    – http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/– http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

  • 8

    According to W3C ..

    • The DOM is a “Platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents”

  • 9

    Generating The DOM

    Parser

    XML Document

    Dom Tree

    Root ElementChild Element

    TextChild Element

    Text

  • 10

    DOM API for XML– Provides access to an in-memory tree representation of the

    XML Document– Performs parsing of the document to load into memory– Returns a handle to the root element– Can search for any node in the DOM– Can add or delete elements, attributes etc.– Can transform the DOM into a new XML Document– Can work with Document fragments

  • 11

    • • • • • • Frank Rizzo• 1212 W 304th Street• New York• New York• 10011• • 212-555-1212• 212-555-1342• 212-555-1115• • [email protected]• http://abc.com • • • • • Sol Rosenberg• 1162 E 412th Street• New York• New York• 10011• • 212-555-1818• 212-555-1828• 212-555-1521• • [email protected]• www.abc.org • Rosenberg's Shoes & Glasses• Sol collects Civil War artifacts.• •

    contacts.xmlagain

    Example DOM:

    The XML document

  • 12

    Example DOM: The DOM treedocument

    xml contacts

    contact

    name

    address

    city

    contact

    name

    address

    city

    state

    zip

    phone

    email

    web

    company

    company

    notes

    voicefax

    mobile

  • 13

    The DOM tree is auto-generated by most XML editors, such as the one

    we see here from

    Data tree (generated by ). Needs

    only the xml file to be produced

  • 14

    .NET Supports XML• XML 1.0

    • http://www.w3.org/TR/1998/REC-xml-19980210• XML Namespaces

    • http://www.w3.org/TR/1999/REC-xml-names-19990114/• XML Schemas

    • http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/• http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/

    • XPath expressions • http://www.w3.org/TR/1999/REC-xpath-19991116

    • XSL/T transformations • http://www.w3.org/TR/1999/REC-xslt-19991116

    • DOM Level 1 and Level 2 Core • http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/• http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

    • More … (later)

  • 15

    Processing XML data in .NET

    • XmlReader: Reading XML data

    • XmlDocument, XmlNode: Object model for XML data (DOM)

    • XmlWriter: Wrting XML data

    • XPathNavigator: XPath selections

    • XslTransform: Transformation of XML documents

    XslTranform

    XslTransform

    XmlDocument

    XSLT Stylesheet

    XmlDocument

    XmlReader XmlWriter

    XPath

    XPathNavigator

  • 16

    XML Namespaces in .NET

    System.Xml

    .Serialization

    .Schema

    .XPath

    .Xsl

    From the actual .NET documentation.

  • 17

    XML Namespaces in .NET…/System.Xml

    .Serialization

    .Schema

    .XPath.Xsl

    EntityHandlingFormattingNameTableReadStateTreePositionValidationWriteStateXmlAttributeXmlAttributeCollectionXmlCDataSectionXmlCharacterData

    XmlCharTypeXmlCommentXmlConvertXmlDataDocumentXmlDeclarationXmlDocumentXmlDocumentFragmentXmlDocumentTypeXmlElementXmlEntityXmlEntityReferenceXmlNamedNodeMap

    XmlNodeXmlNodeReaderXmlNodeTypeXmlNotationXmlReaderXmlSpaceXmlTextXmlTextReaderXmlTextWriterXmlUrlResolverXmlWhitespaceXmlWriter...

  • 18

    System.Xml Namespace• Overall namespace for classes that provide XML support in .NET.• Contains classes for creating, editing, navigating XML documents• Reading, writing and manipulating documents via the DOM

    – Use the XmlDocument class for XML documents

    • Classes that correspond to every “type” of XML “element”:– XmlElement, XmlAttribute, XmlComment, etc

  • 19

    XmlReader

    • Abstract base class for reading XML• Reads in depth-first order

    – Same order as textual XML data

    • Fast, forward-only (cannot jump within XML document), non-cached XML stream reader.

    • .NET’s implementation of SAX (Simple API for XML)

    • Implementations are:

    – XmlTextReader: efficient, no immediate storage of elements

    – XmlValidatingReader: validates document against DTD or XSD

    – XmlNodeReader: reading from an XmlNode (DOM)

  • 20

    XmlReader

    public abstract class XmlReader {

    public abstract string Name { get; } public abstract string LocalName { get; } public abstract string Value { get; } public abstract XmlNodeType NodeType { get; } public abstract int AttributeCount { get; } public abstract int Depth { get; }

    public abstract bool Read(); public virtual void Skip(); public abstract string GetAttribute(int i);

    public abstract void Close(); ...

    }

    Properties of current element•full name•local name•value•type•number of attributes•depth in document

    •Reading of next element •Skipping the current element and its subs •Getting the element‘s attributes

    Closing the reader

  • 21

    XmlWriter

    • Abstract base classes for writing XML• Fast, forward-only, non-cached XML stream writer• Base class for XmlTextWriter

  • 22

    XmlTextReader & XmlTextWriter

    • Derived from the XmlReader & XmlWriter abstract classes• Implement all the functionality defined by their base classes• Designed to work with a text based stream

    – As opposed to an in-memory DOM

    • XmlTextReader methods support reading XML elements– Read, MoveToElement, ReadString, etc

    • XmlTextWriter methods support writing XML elements– WriteDocType, WriteComment, WriteName, etc

  • 23

    XML in .NET XmlTextReader

    • Forward-only, read-only, non-cached access to stream-based XML data

    • Implements XmlReader• Access to data by parsing text input from:

    – Streams– TextReader objects– Strings

    • Properties and methods to view elements and attributes• Event support for validation

  • 24

    XML in .NET XmlTextReader coding bits (C#)

    XmlTextReader reader = new XmlTextReader(“c:\\Sample.xml”);while (reader.Read()) {

    ...}

  • 25

    A C# example using the XmlTextReader class … using System;using System.Xml;// find and print all addresses in file contacts.xml

    namespace ConsoleApplication1XmlTextReader{

    class Class1{

    static void Main(string[] args){

    XmlTextReader r; r = new XmlTextReader("E:\\4413 -- e-commerce

    course\\xmlTest\\ConsoleApplication1XmlTextReader\\bin\\Debug\\contacts.xml");while (r.Read()) {

    if (r.IsStartElement("address")) {

    r.Read(); // read the valueConsole.WriteLine("{0}, ", r.Value);

    }}r.Close();

    }}

    }

  • 26

    The output …

  • 27

    XmlTextWriter coding bits (C#)

    XmlTextWriter writer = new XmlTextWriter (“c:\Sample.xml”, null);writer.WriteStartDocument(); // Write the declarationwriter.WriteStartElement(“ROOT”); // Write the root elementwriter.WriteEndElement(); // Write the close tag of rootwriter.Flush(); // Write XML to filewriter.Close(); // Close writer

  • 28

    XmlDocument

    • Derived from the XmlNode class• Represents an entire (in memory) XML document• Supports DOM Level 1 and Level 2 Core functionality

    • Reading & writing built on top of XmlReader & XmlWriter

    • Load a document and generate the DOM– Using: URI, file, XmlReader, XmlTextReader or Stream

  • 29

    XML in .NET XmlDocument

    • Implements W3C XML Document Object Model (DOM) Level 1 and Level 2 specifications

    • Implements XmlNode– XML elements are represented by XmlNode objects

    • Represents an entire XML document – Construction of object structure in main memory

    – All nodes are available to view/manipulate (efficient manipulation of XML data, but not efficient in terms of space).

    • Cached in memory• Events for changing, inserting and removing nodes (i.e., implements the

    SAX).

  • 30

    Class XmlDocument …public class XmlDocument : XmlNode {

    public XmlDocument();

    public XmlElement DocumentElement { get; } public virtual XmlDocumentType DocumentType { get; }

    public virtual void Load(Stream in); public virtual void Load(string url); public virtual void LoadXml(string data);

    public virtual void Save(Stream out); public virtual void Save(string url);

    Root element

    Document type (DOCTYPE declaration)

    Loading the XML data

    Saving

  • 31

    Class XmlDocument …/

    public event XmlNodeChangedEventHandler NodeChanged;public event XmlNodeChangedEventHandler NodeChanging;public event XmlNodeChangedEventHandler NodeInserted;public event XmlNodeChangedEventHandler NodeInserting;public event XmlNodeChangedEventHandler NodeRemoved;public event XmlNodeChangedEventHandler NodeRemoving;

    }

    public virtual XmlDeclaration CreateXmlDeclaration(string version, string encoding, string standalone);

    public XmlElement CreateElement(string name);public XmlElement CreateElement

    (string qualifiedName, string namespaceURI);public virtual XmlElement CreateElement

    (string prefix, string lName, string nsURI);public virtual XmlText CreateTextNode(string text);public virtual XmlComment CreateComment(string data);

    Events

    Creation of:•declaration node•elements •text nodes •comments

  • 32

    XML in .NET XmlDocument coding bits…

    XmlDocument myXmlDoc = new XmlDocument();myXmlDoc.Load(“c:\\Sample.xml”);

    Load an XML doc in memory

    XmlDocument doc = new XmlDocument();XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null);doc.AppendChild(decl);

    Create new document and

    add declaration

  • 33

    XmlDocument coding bits…

    XmlElement rootElem = doc.CreateElement(“contacts");rootElem.SetAttribute(“myAttribute", "1");doc.AppendChild(rootElem);

    contacts

    myAttribute1

  • 34

    XmlDocument coding bits…XmlElement aContact = doc.CreateElement(“contact");aContact.SetAttribute("id", "1");XmlElement f = doc.CreateElement("firstname");f.AppendChild(doc.CreateTextNode(“Frank"));

    aContact.AppendChild(f);XmlElement l = doc.CreateElement("lastname");l.AppendChild(doc.CreateTextNode(“Rizzo”));

    aContact.AppendChild(l);

    Frank Rizzo

    Create and add contacts element and subelements

    contacts myAttribute1

    contactId1

    firstnameFrank

    lastnameRizzo

  • 35

    XmlDocument coding bits … (C#) using System.Xml;//Create an XmlDocument, Load it, Write it to the Console

    //One way:XmlDocument xDoc = new XmlDocument();xDoc.Load( “C:\\myData.xml");xDoc.Save( Console.Out);

    //Second way (Use a XmlTextReader to read the XML):XmlDocument xDoc = new XmlDocument();XmlTextReader reader = new XmlTextReader(“C:\\myData.xml");xDoc.Load( reader );xDoc.Save( Console.Out);

    //Third way (Use a XmlTextWriter to output the XML document):XmlTextWriter writer = new XmlTextWriter( Console.Out );writer.Formatting = Formatting.Indented;xDoc.WriteContentTo( writer );writer.Flush();Console.WriteLine();writer.Close();

  • 36

    System.Xml.XslNamespace

    • Provides support for XSL Transformations• Some of the classes:

    – XsltTransform: Transforms using a stylesheet– (XsltException: Used to handle transformation

    exceptions)

    • Four simple steps to perform a transformation1. Instantiate a XsltTransform object2. Load a stylesheet3. Load the data (xml file) 4. Transform!

  • 37

    Coding bits … using System.Xml.Xsl;

    // 1. Create a XslTransform object XslTransform xslt = new XslTransform();

    // 2. Load an XSL stylesheetxslt.Load("http://somewhere/favorite.xsl");

    // 3 & 4. Load the XML data file & transform!xslt.Transform(“http://somewhere/mydata.xml”,

    “C:\\somewhere_else\\TransformedXmlOutput.xml” );

  • 38

    Example…(XSLT)

    Upon clicking the button, xsl and xml documents are

    opened and a XSL Transform is performed.

    The progress of the process is displayed in the white

    area, and upon completion of the process the browser is opened and the resulting

    HTML document is displayed.

  • 39

    Example (XSLT) …/

    In the XSLT, the fax numbers of the

    contacts.xml file are extracted.

  • 40

    The code … using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.Xml.Xsl;

    namespace WindowsApplication1XSLT{

    /// /// Summary description for Form1./// public class Form1 : System.Windows.Forms.Form{

    private System.Windows.Forms.Button button1;private System.Windows.Forms.ListBox listBox1;/// /// Required designer variable./// private System.ComponentModel.Container components = null;

    public Form1(){

    //// Required for Windows Form Designer support//InitializeComponent();

    //// TODO: Add any constructor code after InitializeComponent

    call//

    }

    Declare the button and the ListBox

    (white area).

    Use the appropriate namespace

  • 41

    …/// /// Clean up any resources being used./// protected override void Dispose( bool disposing ){

    if( disposing ){

    if (components != null) {

    components.Dispose();}

    }base.Dispose( disposing );

    }

    #region Windows Form Designer generated code/// /// Required method for Designer support - do not modify/// the contents of this method with the code editor./// private void InitializeComponent(){

    this.button1 = new System.Windows.Forms.Button();this.listBox1 = new System.Windows.Forms.ListBox();this.SuspendLayout();// // button1// this.button1.Location = new System.Drawing.Point(80, 56);this.button1.Name = "button1";this.button1.Size = new System.Drawing.Size(136, 24);this.button1.TabIndex = 0;this.button1.Text = "perform XSLT";this.button1.Click += new System.EventHandler(this.button1_Click);

    Hook up the button to the

    event mechanism of C#

    Create the components.

  • 42

    …//

    // listBox1// this.listBox1.Location = new System.Drawing.Point(48, 120);this.listBox1.Name = "listBox1";this.listBox1.Size = new System.Drawing.Size(184, 95);this.listBox1.TabIndex = 1;// // Form1// this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);this.ClientSize = new System.Drawing.Size(292, 273);this.Controls.Add(this.listBox1);this.Controls.Add(this.button1);this.Name = "Form1";this.Text = "Form1";this.ResumeLayout(false);

    }#endregion

    /// /// The main entry point for the application./// [STAThread]static void Main() {

    Application.Run(new Form1());}

    Start the program

    Add the GUI components to the Form

  • 43

    …/private void button1_Click(object sender, System.EventArgs e){

    // 1. Create a XslTransform object XslTransform xslt = new XslTransform();

    // 2. Load an XSL stylesheet

    listBox1.Items.Add("Loading .xsl file ..");

    xslt.Load("E:\\4413 -- e-commerce course\\xmlTest\\contactsFaxes.xsl");

    listBox1.Items.Add(" .... xsl file LOADED!");

    // 3 & 4. Load the XML data file & transform!

    listBox1.Items.Add(" Performing xls transformation ...");

    xslt.Transform("E:\\4413 -- e-commerce course\\xmlTest\\contacts.xml","E:\\4413 -- e-commerce

    course\\xmlTest\\TransformedContactsXmlOutput.html", null );

    listBox1.Items.Add(" ... xls transformation completed!");listBox1.Items.Add("\n");listBox1.Items.Add("... wait for display!");

    System.Diagnostics.Process.Start("IExplore", "E:\\4413 -- e-commerce course\\xmlTest\\TransformedContactsXmlOutput.html");

    }}}

    Create Transform

    object

    Load the .xlsfile

    Perform the transformation on the

    given xml file, using the given xsl file.

    Invoke Internet Explorer and open the resulting html file.

  • 44

    XML in .NETCore Classes in System.XML

    XmlTextWriterXmlWriter

    XmlTextReader

    XmlNodeReader

    XmlValidatingReader

    XmlReader (SAX in .NET)

    XmlDocument (DOM in .NET)

    XmlLinkedNode

    XmlElement

    XmlAttribute

    XmlDataDocument

    XmlNode

    Concrete (Derived) ClassAbstract (Base) Class

    Good news!!!: visual studio .net documentation

    contains code examples that use the features of these classes.

  • 45

    XML in .NET XmlNode

    • Represents a single node in a XML document hierarchy.

    • An abstract class.• Properties and methods to

    – traverse XML document hierarchy.– query properties. Support for XPath expressions

    through IXPathNavigable interface– view, modify, copy, delete nodes– Can select and navigate a subset of a document

  • 46

    XmlNode class …

    public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable {

    public abstract string Name { get; }public abstract string LocalName { get; }public abstract XmlNodeType NodeType { get; }public virtual string Value { get; set; }public virtual XmlAttributeCollection Attributes { get; }public virtual XmlDocument OwnerDocument { get; }public virtual bool IsReadOnly { get; }public virtual bool HasChildNodes { get; }public virtual string Prefix { get; set; }

    public virtual XmlNodeList ChildNodes { get; }public virtual XmlNode FirstChild { get; }public virtual XmlNode LastChild { get; }public virtual XmlNode NextSibling { get; } public virtual XmlNode PreviousSibling { get; } public virtual XmlNode ParentNode { get; }public virtual XmlElement this[string name] { get; }public virtual XmlElement this[string localname, string ns] { get; }

    Properties of node (name, value, attributes, etc).

    Accessing adjacent nodes (children, siblings, parent, etc)

  • 47

    XmlNode class …/...public virtual XmlNode AppendChild(XmlNode newChild);public virtual XmlNode PrependChild(XmlNode newChild);public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild);public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild);public virtual XmlNode RemoveChild(XmlNode oldChild);public virtual void RemoveAll();

    public XPathNavigator CreateNavigator();public XmlNodeList SelectNodes(string xpath); public XmlNode SelectSingleNode(string xpath);

    public abstract void WriteContentTo(XmlWriter w); public abstract void WriteTo(XmlWriter w); ...

    }

    Adding and removing nodes

    Selection of nodes

    Writing

  • 48

    XML in .NET XmlLinkedNode

    • Implements XmlNode• Retrieves the node immediately preceding or

    following the current node• An abstract class from which XmlElement is

    derived– Declaration:

    public abstract class XmlLinkedNode : XmlNode

  • 49

    XML in .NET XmlElement

    • Represents an element in the DOM tree• Properties and methods to view, modify,

    and create element objects– Declaration:

    – Code example:public class XmlElement : XmlLinkedNode

    XmlDocument myXmlDoc = new XmlDocument();myXmlDoc.Load (“c:\\Sample.xml”);

    // DocumentElement retrieves the root elementXmlElement root = myXmlDoc.DocumentElement;

  • 50

    XML in .NET XmlAttribute

    • Implements XmlNode• Represents an attribute of an XmlElement• Valid and/or default values defined by

    schema– Declaration:

    public class XmlAttribute : XmlNode

  • 51

    XML in .NETXmlAttribute

    • Coding bits:

    XmlDocument myXmlDoc = new XmlDocument();myXmlDoc.Load (“c:\\Sample.xml”);

    // Get the attribute collection of the root elementXmlAttributeCollection attrColl = myXmlDoc.DocumentElement.Attributes;

    // Create a new attribute and set its value to “1”.XmlAttribute newAttr = myXmlDoc.CreateAttribute(“value”);newAttr.Value = “1”;

    // Append the new attribute to the collectionattrColl.Append(newAttr);

  • 52

    XPath• XPath is a language for identification of elements in an XML document

    • XPath expression (location path) selects a set of nodes

    • A location path consists of location steps, which are separated by "/"

    //step/step/step/

    Examples of location paths:

    "*" selects all nodes

    “/contacts/*” selects all elements under the contacts elements

    “/contacts/contact[1]” returns the first contact element of the contacts elements

    “/contacts/*/firstname” returns the firstname elements under the contacts elements

  • 53

    XPath• Extends path expressions with query facility• XPath views an XML document as a tree

    – Root of the tree is a node which does notcorrespond to anything in the document

    – Internal nodes are XML elements– Leaves are either

    • Attributes• Text nodes• Comments• Other things that we didn’t discuss (processing instructions, …)

  • 54

    XPath Document TreeRoot of XML documentRoot of XML tree

  • 55

    Document Corresponding to the Tree• A fragment of the report document that we used frequently

    JohnDoeU2

    BartSimpsonU4

  • 56

    XPath Basics• An XPath expression takes a document tree as

    input and returns a set of nodes of the tree• Expressions that start with / are absolute path absolute path

    expressionsexpressions– Expression / – returns root node of XPath tree–– /Students/Student/Students/Student – returns all StudentStudent-elements that

    are children of StudentsStudents elements, which in turn must be children of the root

    –– /Student/Student – returns empty set (no such children at root)

  • 57

    XPath Basics …/CurrentCurrent (or contextcontext node) – exists during the evaluation of XPath expressions . – denotes the current node; .. – denotes the parent

    foo/barfoo/bar – returns all bar bar elements that are children of foofoo nodes, which in turn are children of the current node ../foo/bar/foo/bar – same..../abc/cde/abc/cde – all children of cde, which is a child of abc, under the

    parent of the current node

    Expressions that don’t start with / are relativerelative (to the current node)

  • 58

    Attributes, Text, etc.

    /Students/Student//Students/Student/@@StudentIdStudentId – returns the StudentIdStudentId attribute of Student (Student (which (Student) is a child of StudentsStudents, which are children of the root)/Students/Student/Name/Last//Students/Student/Name/Last/text(text( )) –returns the text children of Last children of …//comment( )comment( ) –– returns comment nodes under root

    Denotes an attribute

  • 59

    Overall Idea and Semantics• An XPath expression is:

    locationStep1/locationStep2/…locationStep1/locationStep2/…•• Location stepLocation step:

    Axis::nodeSelector[predicate]Axis::nodeSelector[predicate]• Navigation axisaxis:

    • child, parent – have seen• ancestor, descendant, ancestor-or-self, descendant-or-self• some other

    •• Node selectorNode selector: node name or wildcard; e.g.,– ./child::Student (we used ./Student, which is an abbreviation)– ./child::* – any e-child (abbreviation: ./*)

    •• PredicatePredicate: a selection condition; e.g.,Students/Student[CourseTaken/@CrsCode = “CS532”]

    This is called fullfull syntax.We used abbreviatedabbreviated syntax before.Full syntax is better for describing

    meaning. Abbreviated syntax is better for programming.

  • 60

    XPath Semantics•• locationStep1/locationStep2/…locationStep1/locationStep2/… means:

    – Find all nodes specified by locationStep1locationStep1– For each such node N:

    • Find all nodes specified by locationStep2locationStep2 using N as the current node

    • Take union

    – For each node returned by locationStep2locationStep2 do the same

    •• locationSteplocationStep = axis::node[predicate]axis::node[predicate]– Find all nodes specified by axis::nodeaxis::node– Select only those that satisfy predicatepredicate

  • 61

    More on Navigation Primitives• 1st StudentStudent child of StudentsStudents:

    /StudentsStudents/StudentStudent[1]• last StudentStudent elements within Students

    /Students//Students/Student[Student[lastlast()()]]

  • 62

    XPath Queries – Examples• Students who have taken CS532:

    – //Student[CrsTaken/@CrsCode=“CS532”]

    • Students who have either a first name or have taken a course in some semester or have status U4– //Student[Name/First or CrsTaken/@Semester or Status/text() = “U4”]

  • 63

    Class XPathNavigator allows navigation in document.

    public abstract class XPathNavigator : ICloneable {

    public abstract string Name { get; }public abstract string Value { get; }public abstract bool HasAttributes { get; }public abstract bool HasChildren { get; }

    public virtual XPathNodeIterator Select(string xpath);public virtual XPathNodeIterator Select(XPathExpression expr);public virtual XPathExpression Compile(string xpath);

    public abstract bool MoveToNext();public abstract bool MoveToFirstChild();public abstract bool MoveToParent();// etc

    }

    public interface IXPathNavigable {XPathNavigator CreateNavigator();

    }

    Properties of current node

    Selection of nodes by XPathexpression

    Moving to adjacent nodes

    IXPathNavigable (implemented by XmlNode) returns XPathNavigator

  • 64

    XPathNavigator

    • Code example:

    XmlDocument myXmlDoc;myXmlDoc.Load (“c:\\Sample.xml”);

    XPathNavigator nav = myXmlDoc.CreateNavigator();

    nav.MoveToRoot(); // move to root elementnav.MoveToNext(); // move to next element

    Load XmlDocumentand create

    XPathNavigator

  • 65

    XPathNavigator

    XPathNodeIterator iterator = nav.Select("/contacts/*/name");while (iterator.MoveNext())

    Console.WriteLine(iterator.Current.Value);

    Select name elements, iterate over selected elements and put out name

    values.

    XPathExpression expr = nav.Compile("/contacts/contact[name=‘Frank Rizzo’]/email");iterator = nav.Select(expr);while (iterator.MoveNext()) Console.WriteLine(iterator.Current.Value);

    For better run-time efficiency compile expression and use compiled expression.

  • 66

    XPathNavigator

    • Example: iterate over a subset of nodesXmlDocument doc = new XmlDocument();doc.Load("person.xml");XPathNavigator nav = doc.CreateNavigator();XPathNodeIterator iter = nav.Select("/person/name");while (iter.MoveToNext ()) {// process selection here… with iter.Current.Value

    }

    • Example: sum all Prices in a documentpublic static void SumPriceNodes(XPathNavigator nav) {// in this case, evaluate returns a numberConsole.WriteLine("sum=" + nav.Evaluate("sum(//Price)"));

    }

  • 67

    C# and .NETHow to access the C# API. Select

    “Start | Programs | Microsoft Visual Studio .NET 2003 | Microsoft Visual Studio .NET 2003 Documentation”

    The XML APIs

  • 68

    The C# (and .NET in general) API

    Choose …

  • 69

    …/

    System is a major namespace for C#

    XML (6)Other conditional tagsExampleResult …SortingResult …The XML DOMAccording to W3C ..Generating The DOMDOM API for XMLExample DOM: The DOM treeThe DOM tree is auto-generated by most XML editors, such as the one we see here from .NET Supports XMLProcessing XML data in .NETXML Namespaces in .NETXML Namespaces in .NET…/System.Xml NamespaceXmlReaderXmlReaderXmlWriterXmlTextReader & XmlTextWriterXML in .NET XmlTextReaderXML in .NET XmlTextReader coding bits (C#)A C# example using the XmlTextReader class …The output …XmlTextWriter coding bits (C#)XmlDocumentXML in .NET XmlDocumentClass XmlDocument …Class XmlDocument …/XML in .NET XmlDocument coding bits…XmlDocument coding bits…XmlDocument coding bits…XmlDocument coding bits … (C#)System.Xml.Xsl NamespaceCoding bits …Example…(XSLT)Example (XSLT) …/The code …………/XML in .NETCore Classes in System.XMLXML in .NET XmlNodeXmlNode class …XmlNode class …/XML in .NET XmlLinkedNodeXML in .NET XmlElementXML in .NET XmlAttributeXML in .NET XmlAttributeXPathXPathXPath Document TreeDocument Corresponding to the TreeXPath BasicsXPath Basics …/Attributes, Text, etc.Overall Idea and SemanticsXPath SemanticsMore on Navigation PrimitivesXPath Queries – ExamplesClass XPathNavigator allows navigation in document.XPathNavigatorXPathNavigatorXPathNavigatorC# and .NETThe C# (and .NET in general) API…/