SlideShare ist ein Scribd-Unternehmen logo
1 von 63
Downloaden Sie, um offline zu lesen
Tool Development
Chapter 04: XML
Nick Prühs
Assignment Solution #3
DEMO
2 / 58
Objectives
• To get an overview of the structure of XML
documents in general
• To learn how to read and write XML documents in
.NET
• To understand advanced concepts of XML
processing such as XPath and XSLT
3 / 58
XML Fundamentals
• Short for Extensible Markup Language
• Logical structuring of data
• Domain-specific languages
• Content-oriented markup (in contrast to HTML)
• Self-descriptive structure
• Tags
• XML Schema
• Structural variations (e.g. variable child node count)
4 / 58
XML Benefits
• Human-readable
• Automated document validation
• Used in machine-machine communication (e.g.
web services)
5 / 58
XML Processing
6 / 58
XML Document Example
XML (GraphML)
7 / 58
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<node id="n2"/>
<node id="n3"/>
<edge source="n0" target="n2"/>
<edge source="n1" target="n2"/>
<edge source="n2" target="n3"/>
</graph>
</graphml>
XML Document Example
XML (Collada)
8 / 58
<node id="here">
<translate sid="trans">1.0 2.0 3.0</translate>
<rotate sid="rot">1.0 2.0 3.0 4.0</rotate>
<matrix sid="mat">
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0
9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0
</matrix>
</node>
XML Document Example
XML (XAML)
9 / 58
<Window x:Class="LevelEditor.View.NewMapWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="New Map" Height="300" Width="300">
<StackPanel>
<DockPanel>
<TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Map Width:</TextBlock>
<TextBox Name="TextBoxMapWidth" Margin="5">32</TextBox>
</DockPanel>
<DockPanel>
<TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Map Height:</TextBlock>
<TextBox Name="TextBoxMapHeight" Margin="5">32</TextBox>
</DockPanel>
<DockPanel>
<TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Default Tile:</TextBlock>
<StackPanel Margin="5" Name="DefaultTilePanel" />
</DockPanel>
<Button Click="OnCreateMapClicked">Create New Map</Button>
</StackPanel>
</Window>
XML Tree Structure
10 / 58
Window
StackPanel
DockPanel
TextBlock TextBox
DockPanel
TextBlock TextBox
DockPanel
TextBlock StackPanel
Button
XML Node Types
• Elements
• Document Element
• Content
• Attributes
• Comment
• Namespaces
• Processing Instructions
11 / 58
XML Elements
• Main parts of XML documents
• Boundaries defined by start and end tags
• Consist of name, attributes and content
• Can be nested
• Root element is called document element
• Always exactly one document element
12 / 58
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<edge source="n0" target="n1"/>
</graph>
XML Content
• Text between start and end tags of an element
• Either simple, complex or mixed
13 / 58
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<edge source="n0" target="n1"/>
</graph>
XML Attributes
• Associate name-value pairs with elements
• May appear within start tags, only
• Order doesn’t matter
• Unique per element
14 / 58
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<edge source="n0" target="n1"/>
</graph>
XML Comments
• Not part of document data
• XML processors may (but don’t need to) retrieve
text comments
• Double-hyphen (“- -”) must not occur within
comments
15 / 58
<!-- Connect both nodes. -->
<edge source="n0" target="n1"/>
XML Namespaces
• Used for distinguishing nodes with same names
• Bound to an URI by the xmlns attribute
16 / 58
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns">
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<edge source="n0" target="n1"/>
</graph>
</graphml>
Writing XML in .NET
• Abstract base class XmlWriter
• Non-cached
• Forward-only
• Write-only
• Writes to stream or file
• Verifies that the characters are legal XML characters
and that element and attribute names are valid
XML names
• Verifies that the XML document is well formed
17 / 58
Creating an XmlWriter
• XmlWriter instances are created using the static
Create method
• XmlWriterSettings class is used to specify the set
of features you want to enable on the XmlWriter
object
• XmlWriterSettings can be reused to create
multiple writer objects
• Allows adding features to an existing writer
• Create method can accept another XmlWriter object
• Underlying XmlWriter object can be another XmlWriter
instance that you want to add additional features to
18 / 58
Creating an XmlWriter
C#
19 / 58
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = "t"
};
XmlWriter writer = XmlWriter.Create("books.xml", settings);
XmlWriterSettings Defaults
Property Description Default Value
CheckCharacters
Whether to do character
checking.
true
Encoding Type of text encoding to use. Encoding.UTF8
Indent Whether to indent elements. false
IndentChars
Character string to use when
indenting.
Two whitespaces
NewLineChars
Character string to use for line
breaks.
rn
NewLineOnAttributes
Whether to write attributes on a
new line.
false
20 / 58
Writing XML
with the XmlWriter
21 / 58
Member Name Description
WriteElementString Writes an entire element node, including a string value.
WriteStartElement Writes the specified start tag.
WriteEndElement Closes one element and pops the corresponding namespace scope.
WriteElementString Writes an element containing a string value.
WriteValue
Takes a CLR object and converts the input value to the desired output type using the
XML Schema definition language (XSD) data type conversion rules. If the CLR object is a
list type, such as IEnumerable, IList, or ICollection, it is treated as an array of the
value type.
WriteAttributeString Writes an attribute with the specified value.
WriteStartAttribute Writes the start of an attribute.
WriteEndAttribute Closes the previous WriteStartAttribute call.
WriteNode Copies everything from the source object to the current writer instance.
WriteAttributes Writes out all the attributes found at the current position in the XmlReader.
Writing XML Elements
C#
22 / 58
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
// Write XML data.
writer.WriteStartElement("book");
writer.WriteElementString("title", "Awesome book");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();
}
Writing XML Attributes
C#
23 / 58
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
// Write XML data.
writer.WriteStartElement("book");
// Write the genre attribute.
writer.WriteAttributeString("genre", "novel");
writer.WriteElementString("title", "Awesome book");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();
}
Namespace Handling
• XmlWriter maintains a namespace stack
corresponding to all the namespaces defined in the
current namespace scope
• WriteElementString, WriteStartElement,
WriteAttributeString and WriteStartAttribute
methods have overloads that allow you to specify a
namespace URI
24 / 58
Namespace Handling
C#
25 / 58
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = "t"
};
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
// Write XML data.
writer.WriteStartElement("book");
// Write the namespace declaration.
writer.WriteAttributeString("xmlns", "bk", null, "http://www.example.com/book");
// Write the genre attribute.
writer.WriteAttributeString("genre", "novel");
writer.WriteElementString("title", "Awesome book");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();
}
Reading XML in .NET
• Abstract base class XmlReader
• Non-cached
• Forward-only
• Read-only
• Reads from stream or file
• Verifies that the XML document is well formed
• Validates the data against a DTD or schema
26 / 58
Creating an XmlReader
• XmlReader instances are created using the static
Create method
• XmlReaderSettings class is used to specify the set
of features you want to enable on the XmlReader
object
• XmlReaderSettings can be reused to create
multiple reader objects
• Allows adding features to an existing reader
• Create method can accept another XmlReader object
• Underlying XmlReader object can be another XmlReader
instance that you want to add additional features to
27 / 58
Creating an XmlReader
C#
28 / 58
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreWhitespace = true,
IgnoreComments = true
};
XmlReader reader = XmlReader.Create("books.xml", settings);
XmlReaderSettings Defaults
Property Description Default Value
CheckCharacters
Whether to do character
checking.
true
IgnoreComments Whether to ignore comments. false
IgnoreProcessingInstructions
Whether to ignore processing
instructions.
false
IgnoreWhitespace
Whether to ignore insignificant
white space.
false
Schemas
XmlSchemaSet to use when
performing schema validation.
Empty XmlSchemaSet
ValidationType
Whether to perform validation or
type assignment when reading.
ValidationType.None
29 / 58
Working with XmlReader
• Current node refers to the node on which the
reader is positioned
• Move through the data and read the contents of a
node
• Reader is advanced using any of the Read methods
30 / 58
Reading XML Elements
31 / 58
Member Name Description
IsStartElement Checks if the current node is a start tag or an empty element tag.
ReadStartElement Checks that the current node is an element and advances the reader to the next node.
ReadEndElement Checks that the current node is an end tag and advances the reader to the next node.
ReadElementString Reads a text-only element.
ReadToDescendant Advances the XmlReader to the next descendant element with the specified name.
ReadToNextSibling Advances the XmlReader to the next sibling element with the specified name.
IsEmptyElement Checks if the current element has an empty element tag.
After the XmlReader is positioned on an element, the node properties, such as
Name, reflect the element values.
Reading XML Elements
C#
32 / 58
using (XmlReader reader = XmlReader.Create("books.xml"))
{
reader.Read();
reader.ReadStartElement("book");
reader.ReadStartElement("title");
Console.Write("The content of the title element: ");
Console.WriteLine(reader.ReadString());
reader.ReadEndElement();
reader.ReadStartElement("price");
Console.Write("The content of the price element: ");
Console.WriteLine(reader.ReadString());
reader.ReadEndElement();
reader.ReadEndElement();
}
Reading XML Attributes
33 / 58
After MoveToAttribute has been called, the node properties, such as Name, reflect
the properties of that attribute, and not the containing element it belongs to.
Member Name Description
AttributeCount Gets the number of attributes on the element.
GetAttribute Gets the value of the attribute.
HasAttributes Gets a value indicating whether the current node has any attributes.
Item Gets the value of the specified attribute.
MoveToAttribute Moves to the specified attribute.
MoveToElement Moves to the element that owns the current attribute node.
MoveToFirstAttribute Moves to the first attribute.
MoveToNextAttribute Moves to the next attribute.
Reading XML Attributes
C#
34 / 58
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreWhitespace = true
};
using (XmlReader reader = XmlReader.Create("books.xml", settings))
{
while (reader.Read())
{
if (reader.HasAttributes)
{
Console.WriteLine("Attributes of <" + reader.Name + ">");
while (reader.MoveToNextAttribute())
{
Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
}
// Move the reader back to the element node.
reader.MoveToElement();
}
}
}
Reading Typed Data
• XmlReader class permits callers to read XML data and
return values as simple-typed CLR values rather than
strings
• Gets values in the representation that is most
appropriate for the coding job without having to
manually perform value conversions and parsing
• ReadContentAsBoolean, ReadContentAsDateTime,
ReadContentAsDouble, ReadContentAsLong,
ReadContentAsInt, and ReadContentAsString methods are
used to return a specific CLR object
• ReadElementContentAs method is used to read element
content and return an object of the type specified
35 / 58
DOM vs. SAX Parsing
• Simple API for XML (SAX)
• Sequential access
• Required memory is proportional to maximum depth of
the input document
• Document validation requires keeping track of id
attributes, open elements, etc.
• Document Object Model (DOM)
• Operates on the document as a whole
• Required memory is proportional to the entire
document length
36 / 58
Working with XmlDocument
• In-memory tree representation of an XML
document
• Enables navigation and editing of parsed
documents, including adding and removing nodes
• XmlNode object is the basic object in the DOM tree
37 / 58
Working with XmlDocument
C#
38 / 58
// Load XML document.
XmlDocument document = new XmlDocument();
document.Load("books.xml");
// Find book element.
XmlNode bookNode = document["book"];
// Add author element.
XmlElement element = document.CreateElement("author");
XmlText text = document.CreateTextNode("Nick Prühs");
bookNode.AppendChild(element);
element.AppendChild(text);
// Write document to console.
XmlWriter writer = new XmlTextWriter(Console.Out);
document.WriteTo(writer);
Navigating XML Documents
• XML Path Language (XPath) selects nodes from an
XML document
• Each expression is evaluated with respect to a
context node (e.g. “child”)
• Location path consists of a sequence of location
steps
39 / 58
XPath Location Steps
• Axis
• Specifies the tree relationship between the nodes
selected by the location step and the context node
• Node test
• Specifies the node type and expanded-name of the
nodes selected by the location step
• Predicate(s)
• Further refine the set of nodes selected by the location
step
40 / 58
XPath Axes
Axis
Ancestor Selects all ancestors (parent, grandparent, etc.) of the current
node.
Ancestor-or-self Selects all ancestors (parent, grandparent, etc.) of the current
node and the current node itself.
Attribute Selects all attributes of the current node.
Child Selects all children of the current node.
Descendant Selects all descendants (children, grandchildren, etc.) of the
current node.
Descendant-or-self Selects all descendants (children, grandchildren, etc.) of the
current node and the current node itself.
41 / 58
XPath Axes
Axis
Following Selects everything in the document after the closing tag of
the current node.
Following-sibling Selects all siblings after the current node.
Namespace Selects all namespace nodes of the current node
Parent Selects the parent of the current node.
Preceding Selects all nodes that appear before the current node in the
document, except ancestors, attribute nodes and namespace
nodes.
Preceding-sibling Selects all siblings before the current node.
Self Selects the current node.
42 / 58
XPath Node Tests
• node() is true for any node of any type
• * is true for any node of the principal node type.
• child::* will select all element children of the context
node
• attribute::* will select all attributes of the context
node
• comment() is true for any comment node
• text() is true for any text node
• processing-instruction() is true for any
processing instruction
43 / 58
XPath Predicates
Restrict a node-set to select only those nodes for which some
condition is true.
Example:
book[@genre=‘scifi’]
44 / 58
XPath Location Paths
Location step syntax:
axis::nodetest[predicate]
Example:
/books/book/attribute::*
/books/book[@genre=‘scifi’]
45 / 58
XSLT Fundamentals
• Short for Extensible Stylesheet Language
Transformation
• Transforms XML documents into other formats
such as other XML documents, HTML or plain text
• Turing-complete
46 / 58
XSLT Motivation
47 / 58
XSLT Processing
1. Read stylesheet file.
2. Build source tree from input XML document.
3. For each node in the source tree:
1. Process source tree node.
2. Find best-matching template in the stylesheet.
3. Evaluate the template contents.
4. Create node(s) in the result tree.
48 / 58
Common XSLT Elements
Node Description
xsl:apply-templates Specifies that other matches may exist
within that node. If “select” is specified,
only the templates that specify a match
that fits the selected node or attribute
type will be applied.
xsl:choose Contains xsl:when blocks and up to one
xsl:otherwise block.
xsl:for-each Creates a loop which repeats for every
match.
xsl:stylesheet Top-level element. Occurs only once in a
stylesheet document.
xsl:template Specifies processing templates.
xsl:value-of Outputs a variable.
49 / 58
XSLT Example
XML
50 / 58
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="books.xsl" type="text/xsl" ?>
<books>
<book>
<title>Awesome book</title>
<price>19.95</price>
</book>
<book>
<title>Another book</title>
<price>9.95</price>
</book>
</books>
XSLT Example
XSLT
51 / 58
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
XSLT Example
XSLT
52 / 58
<xsl:template match="/books">
<html>
<head>
<title>Transforming books.xml with XSLT</title>
</head>
<body>
<h1>Books</h1>
<table>
<tr>
<th>Title</th>
<th>Price</th>
</tr>
<xsl:apply-templates select="book">
<xsl:sort select="title" />
</xsl:apply-templates>
</table>
</body>
</html>
</xsl:template>
XSLT Example
XSLT
53 / 58
<xsl:template match="book">
<tr>
<td>
<xsl:value-of select="title"/>
</td>
<td>
<xsl:value-of select="price"/>
</td>
</tr>
</xsl:template>
XSLT Example
Rendered HTML
54 / 58
OpenFileDialog Control
Common dialog box that allows a user to specify a
filename for one or more files to open.
Rendered View
55 / 58
OpenFileDialog Control
C#
56 / 58
// Show open file dialog box.
OpenFileDialog openFileDialog = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = ".txt",
Filter = "Text files (.txt)|*.txt",
ValidateNames = true
};
var result = openFileDialog.ShowDialog();
if (result != true)
{
return;
}
// Open text file.
using (var stream = openFileDialog.OpenFile())
{
// Do something.
}
SaveFileDialog Control
Common dialog that allows the user to specify a
filename to save a file as.
Rendered View
57 / 58
SaveFileDialog Control
C#
58 / 58
// Show save file dialog box.
SaveFileDialog saveFileDialog = new SaveFileDialog
{
AddExtension = true,
CheckPathExists = true,
DefaultExt = ".txt",
FileName = "TextFile",
Filter = "Text files (.txt)|*.txt",
ValidateNames = true
};
var result = saveFileDialog.ShowDialog();
if (result != true)
{
return;
}
// Open file stream.
using (var stream = saveFileDialog.OpenFile())
{
// Do something.
}
Assignment #4
1. Save Map
1. Add a new MenuItem “Save As” to your MainWindow,
along with a ToolBar button with tooltip.
2. Allow saving a map file by showing a Save File Dialog
when the Save As command is executed.
1. Map files should be well-formed, valid XML files.
2. Each map file should contain the width and height of the
map, as well as the types of all map tiles.
3. It should not be possible to save a map if there is
none.
59 / 58
Assignment #4
2. Load Map
1. Add a new MenuItem “Open” to your MainWindow,
along with a ToolBar button with tooltip.
2. Add separators to both your toolbar and menu.
3. Allow loading a map file by showing an Open File
Dialog when the Open command is executed.
4. Opening a corrupt or invalid XML file should result in
an error message. The current map should only be
discarded of the map file could be successfully
opened.
60 / 58
References
• MSDN. XML Documents and Data.
http://msdn.microsoft.com/en-
us/library/2bcctyt8%28v=vs.110%29.aspx, May 2016.
• Luttenberger. Internet Applications – Web Services Primer.
Department for Computer Science, CAU Kiel, 2008.
• Brandes, Eiglsperger, Lerner. GraphML Primer.
http://graphml.graphdrawing.org/primer/graphml-primer.html,
May 2016.
• Barnes, Finch. COLLADA – Digital Asset Schema Release 1.5.0
Specification. Sony Computer Entertainment Inc., April 2008.
• Clark, DeRose. XML Path Language (XPath).
http://www.w3.org/TR/xpath/, November 16, 1999.
• w3schools.com. XPath Axes.
http://www.w3schools.com/xsl/xpath_axes.asp, May 2016.
61 / 58
Thank you!
http://www.npruehs.de
https://github.com/npruehs
@npruehs
dev@npruehs.de
5 Minute Review Session
• What are the main benefits of using XML?
• What are the three main XML processing steps?
• Which XML node types do you know?
• How do you properly create XmlWriter instances?
• How do you read typed XML content?
• What is the difference between DOM and SAX
parsing?
• What are the main parts of an XPath location step?
• What is XSLT and how does it work?
63 / 58

Weitere ähnliche Inhalte

Was ist angesagt? (19)

Json
Json Json
Json
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
X FILES
X FILESX FILES
X FILES
 
6 xml parsing
6   xml parsing6   xml parsing
6 xml parsing
 
Ajax
AjaxAjax
Ajax
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured Data
 
Collections
CollectionsCollections
Collections
 
Dom parser
Dom parserDom parser
Dom parser
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
 
Ado.net session11
Ado.net session11Ado.net session11
Ado.net session11
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Parsing XML Data
Parsing XML DataParsing XML Data
Parsing XML Data
 
26xslt
26xslt26xslt
26xslt
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Understanding C# in .NET
Understanding C# in .NETUnderstanding C# in .NET
Understanding C# in .NET
 
Java and XML
Java and XMLJava and XML
Java and XML
 
Iterator
IteratorIterator
Iterator
 

Ähnlich wie Tool Development 04 - XML (20)

XML
XMLXML
XML
 
Xml writers
Xml writersXml writers
Xml writers
 
Xml
XmlXml
Xml
 
Extensible markup language attacks
Extensible markup language attacksExtensible markup language attacks
Extensible markup language attacks
 
Applied xml programming for microsoft 2
Applied xml programming for microsoft  2Applied xml programming for microsoft  2
Applied xml programming for microsoft 2
 
Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12
 
XML
XMLXML
XML
 
Xml session
Xml sessionXml session
Xml session
 
WML Script by Shanti katta
WML Script by Shanti kattaWML Script by Shanti katta
WML Script by Shanti katta
 
XML for beginners
XML for beginnersXML for beginners
XML for beginners
 
Using SP Metal for faster share point development
Using SP Metal for faster share point developmentUsing SP Metal for faster share point development
Using SP Metal for faster share point development
 
Xml and DTD's
Xml and DTD'sXml and DTD's
Xml and DTD's
 
Applied xml programming for microsoft
Applied xml programming for microsoftApplied xml programming for microsoft
Applied xml programming for microsoft
 
XML
XMLXML
XML
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Using SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint developmentUsing SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint development
 
The xml
The xmlThe xml
The xml
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Sax Dom Tutorial
Sax Dom TutorialSax Dom Tutorial
Sax Dom Tutorial
 

Mehr von Nick Pruehs

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsNick Pruehs
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceNick Pruehs
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesNick Pruehs
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayNick Pruehs
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorNick Pruehs
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkNick Pruehs
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud DevelopmentNick Pruehs
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - GitNick Pruehs
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameNick Pruehs
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with PonyNick Pruehs
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationNick Pruehs
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsNick Pruehs
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Nick Pruehs
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard DoNick Pruehs
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - GitNick Pruehs
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - ShadersNick Pruehs
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game PhysicsNick Pruehs
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - LocalizationNick Pruehs
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AINick Pruehs
 

Mehr von Nick Pruehs (20)

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual Effects
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User Interface
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior Trees
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - Gameplay
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud Development
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - Git
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with Pony
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance Optimization
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small Teams
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard Do
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - Git
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - Shaders
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game Physics
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - Localization
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AI
 

Kürzlich hochgeladen

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Kürzlich hochgeladen (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Tool Development 04 - XML

  • 3. Objectives • To get an overview of the structure of XML documents in general • To learn how to read and write XML documents in .NET • To understand advanced concepts of XML processing such as XPath and XSLT 3 / 58
  • 4. XML Fundamentals • Short for Extensible Markup Language • Logical structuring of data • Domain-specific languages • Content-oriented markup (in contrast to HTML) • Self-descriptive structure • Tags • XML Schema • Structural variations (e.g. variable child node count) 4 / 58
  • 5. XML Benefits • Human-readable • Automated document validation • Used in machine-machine communication (e.g. web services) 5 / 58
  • 7. XML Document Example XML (GraphML) 7 / 58 <?xml version="1.0" encoding="UTF-8"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"> <graph id="G" edgedefault="undirected"> <node id="n0"/> <node id="n1"/> <node id="n2"/> <node id="n3"/> <edge source="n0" target="n2"/> <edge source="n1" target="n2"/> <edge source="n2" target="n3"/> </graph> </graphml>
  • 8. XML Document Example XML (Collada) 8 / 58 <node id="here"> <translate sid="trans">1.0 2.0 3.0</translate> <rotate sid="rot">1.0 2.0 3.0 4.0</rotate> <matrix sid="mat"> 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 </matrix> </node>
  • 9. XML Document Example XML (XAML) 9 / 58 <Window x:Class="LevelEditor.View.NewMapWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="New Map" Height="300" Width="300"> <StackPanel> <DockPanel> <TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Map Width:</TextBlock> <TextBox Name="TextBoxMapWidth" Margin="5">32</TextBox> </DockPanel> <DockPanel> <TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Map Height:</TextBlock> <TextBox Name="TextBoxMapHeight" Margin="5">32</TextBox> </DockPanel> <DockPanel> <TextBlock DockPanel.Dock="Left" Width="75" Margin="5">Default Tile:</TextBlock> <StackPanel Margin="5" Name="DefaultTilePanel" /> </DockPanel> <Button Click="OnCreateMapClicked">Create New Map</Button> </StackPanel> </Window>
  • 10. XML Tree Structure 10 / 58 Window StackPanel DockPanel TextBlock TextBox DockPanel TextBlock TextBox DockPanel TextBlock StackPanel Button
  • 11. XML Node Types • Elements • Document Element • Content • Attributes • Comment • Namespaces • Processing Instructions 11 / 58
  • 12. XML Elements • Main parts of XML documents • Boundaries defined by start and end tags • Consist of name, attributes and content • Can be nested • Root element is called document element • Always exactly one document element 12 / 58 <graph id="G" edgedefault="undirected"> <node id="n0"/> <node id="n1"/> <edge source="n0" target="n1"/> </graph>
  • 13. XML Content • Text between start and end tags of an element • Either simple, complex or mixed 13 / 58 <graph id="G" edgedefault="undirected"> <node id="n0"/> <node id="n1"/> <edge source="n0" target="n1"/> </graph>
  • 14. XML Attributes • Associate name-value pairs with elements • May appear within start tags, only • Order doesn’t matter • Unique per element 14 / 58 <graph id="G" edgedefault="undirected"> <node id="n0"/> <node id="n1"/> <edge source="n0" target="n1"/> </graph>
  • 15. XML Comments • Not part of document data • XML processors may (but don’t need to) retrieve text comments • Double-hyphen (“- -”) must not occur within comments 15 / 58 <!-- Connect both nodes. --> <edge source="n0" target="n1"/>
  • 16. XML Namespaces • Used for distinguishing nodes with same names • Bound to an URI by the xmlns attribute 16 / 58 <?xml version="1.0" encoding="UTF-8"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns"> <graph id="G" edgedefault="undirected"> <node id="n0"/> <node id="n1"/> <edge source="n0" target="n1"/> </graph> </graphml>
  • 17. Writing XML in .NET • Abstract base class XmlWriter • Non-cached • Forward-only • Write-only • Writes to stream or file • Verifies that the characters are legal XML characters and that element and attribute names are valid XML names • Verifies that the XML document is well formed 17 / 58
  • 18. Creating an XmlWriter • XmlWriter instances are created using the static Create method • XmlWriterSettings class is used to specify the set of features you want to enable on the XmlWriter object • XmlWriterSettings can be reused to create multiple writer objects • Allows adding features to an existing writer • Create method can accept another XmlWriter object • Underlying XmlWriter object can be another XmlWriter instance that you want to add additional features to 18 / 58
  • 19. Creating an XmlWriter C# 19 / 58 XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "t" }; XmlWriter writer = XmlWriter.Create("books.xml", settings);
  • 20. XmlWriterSettings Defaults Property Description Default Value CheckCharacters Whether to do character checking. true Encoding Type of text encoding to use. Encoding.UTF8 Indent Whether to indent elements. false IndentChars Character string to use when indenting. Two whitespaces NewLineChars Character string to use for line breaks. rn NewLineOnAttributes Whether to write attributes on a new line. false 20 / 58
  • 21. Writing XML with the XmlWriter 21 / 58 Member Name Description WriteElementString Writes an entire element node, including a string value. WriteStartElement Writes the specified start tag. WriteEndElement Closes one element and pops the corresponding namespace scope. WriteElementString Writes an element containing a string value. WriteValue Takes a CLR object and converts the input value to the desired output type using the XML Schema definition language (XSD) data type conversion rules. If the CLR object is a list type, such as IEnumerable, IList, or ICollection, it is treated as an array of the value type. WriteAttributeString Writes an attribute with the specified value. WriteStartAttribute Writes the start of an attribute. WriteEndAttribute Closes the previous WriteStartAttribute call. WriteNode Copies everything from the source object to the current writer instance. WriteAttributes Writes out all the attributes found at the current position in the XmlReader.
  • 22. Writing XML Elements C# 22 / 58 XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; using (XmlWriter writer = XmlWriter.Create("books.xml", settings)) { // Write XML data. writer.WriteStartElement("book"); writer.WriteElementString("title", "Awesome book"); writer.WriteElementString("price", "19.95"); writer.WriteEndElement(); }
  • 23. Writing XML Attributes C# 23 / 58 XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; using (XmlWriter writer = XmlWriter.Create("books.xml", settings)) { // Write XML data. writer.WriteStartElement("book"); // Write the genre attribute. writer.WriteAttributeString("genre", "novel"); writer.WriteElementString("title", "Awesome book"); writer.WriteElementString("price", "19.95"); writer.WriteEndElement(); }
  • 24. Namespace Handling • XmlWriter maintains a namespace stack corresponding to all the namespaces defined in the current namespace scope • WriteElementString, WriteStartElement, WriteAttributeString and WriteStartAttribute methods have overloads that allow you to specify a namespace URI 24 / 58
  • 25. Namespace Handling C# 25 / 58 XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "t" }; using (XmlWriter writer = XmlWriter.Create("books.xml", settings)) { // Write XML data. writer.WriteStartElement("book"); // Write the namespace declaration. writer.WriteAttributeString("xmlns", "bk", null, "http://www.example.com/book"); // Write the genre attribute. writer.WriteAttributeString("genre", "novel"); writer.WriteElementString("title", "Awesome book"); writer.WriteElementString("price", "19.95"); writer.WriteEndElement(); }
  • 26. Reading XML in .NET • Abstract base class XmlReader • Non-cached • Forward-only • Read-only • Reads from stream or file • Verifies that the XML document is well formed • Validates the data against a DTD or schema 26 / 58
  • 27. Creating an XmlReader • XmlReader instances are created using the static Create method • XmlReaderSettings class is used to specify the set of features you want to enable on the XmlReader object • XmlReaderSettings can be reused to create multiple reader objects • Allows adding features to an existing reader • Create method can accept another XmlReader object • Underlying XmlReader object can be another XmlReader instance that you want to add additional features to 27 / 58
  • 28. Creating an XmlReader C# 28 / 58 XmlReaderSettings settings = new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true }; XmlReader reader = XmlReader.Create("books.xml", settings);
  • 29. XmlReaderSettings Defaults Property Description Default Value CheckCharacters Whether to do character checking. true IgnoreComments Whether to ignore comments. false IgnoreProcessingInstructions Whether to ignore processing instructions. false IgnoreWhitespace Whether to ignore insignificant white space. false Schemas XmlSchemaSet to use when performing schema validation. Empty XmlSchemaSet ValidationType Whether to perform validation or type assignment when reading. ValidationType.None 29 / 58
  • 30. Working with XmlReader • Current node refers to the node on which the reader is positioned • Move through the data and read the contents of a node • Reader is advanced using any of the Read methods 30 / 58
  • 31. Reading XML Elements 31 / 58 Member Name Description IsStartElement Checks if the current node is a start tag or an empty element tag. ReadStartElement Checks that the current node is an element and advances the reader to the next node. ReadEndElement Checks that the current node is an end tag and advances the reader to the next node. ReadElementString Reads a text-only element. ReadToDescendant Advances the XmlReader to the next descendant element with the specified name. ReadToNextSibling Advances the XmlReader to the next sibling element with the specified name. IsEmptyElement Checks if the current element has an empty element tag. After the XmlReader is positioned on an element, the node properties, such as Name, reflect the element values.
  • 32. Reading XML Elements C# 32 / 58 using (XmlReader reader = XmlReader.Create("books.xml")) { reader.Read(); reader.ReadStartElement("book"); reader.ReadStartElement("title"); Console.Write("The content of the title element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadStartElement("price"); Console.Write("The content of the price element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadEndElement(); }
  • 33. Reading XML Attributes 33 / 58 After MoveToAttribute has been called, the node properties, such as Name, reflect the properties of that attribute, and not the containing element it belongs to. Member Name Description AttributeCount Gets the number of attributes on the element. GetAttribute Gets the value of the attribute. HasAttributes Gets a value indicating whether the current node has any attributes. Item Gets the value of the specified attribute. MoveToAttribute Moves to the specified attribute. MoveToElement Moves to the element that owns the current attribute node. MoveToFirstAttribute Moves to the first attribute. MoveToNextAttribute Moves to the next attribute.
  • 34. Reading XML Attributes C# 34 / 58 XmlReaderSettings settings = new XmlReaderSettings { IgnoreWhitespace = true }; using (XmlReader reader = XmlReader.Create("books.xml", settings)) { while (reader.Read()) { if (reader.HasAttributes) { Console.WriteLine("Attributes of <" + reader.Name + ">"); while (reader.MoveToNextAttribute()) { Console.WriteLine(" {0}={1}", reader.Name, reader.Value); } // Move the reader back to the element node. reader.MoveToElement(); } } }
  • 35. Reading Typed Data • XmlReader class permits callers to read XML data and return values as simple-typed CLR values rather than strings • Gets values in the representation that is most appropriate for the coding job without having to manually perform value conversions and parsing • ReadContentAsBoolean, ReadContentAsDateTime, ReadContentAsDouble, ReadContentAsLong, ReadContentAsInt, and ReadContentAsString methods are used to return a specific CLR object • ReadElementContentAs method is used to read element content and return an object of the type specified 35 / 58
  • 36. DOM vs. SAX Parsing • Simple API for XML (SAX) • Sequential access • Required memory is proportional to maximum depth of the input document • Document validation requires keeping track of id attributes, open elements, etc. • Document Object Model (DOM) • Operates on the document as a whole • Required memory is proportional to the entire document length 36 / 58
  • 37. Working with XmlDocument • In-memory tree representation of an XML document • Enables navigation and editing of parsed documents, including adding and removing nodes • XmlNode object is the basic object in the DOM tree 37 / 58
  • 38. Working with XmlDocument C# 38 / 58 // Load XML document. XmlDocument document = new XmlDocument(); document.Load("books.xml"); // Find book element. XmlNode bookNode = document["book"]; // Add author element. XmlElement element = document.CreateElement("author"); XmlText text = document.CreateTextNode("Nick Prühs"); bookNode.AppendChild(element); element.AppendChild(text); // Write document to console. XmlWriter writer = new XmlTextWriter(Console.Out); document.WriteTo(writer);
  • 39. Navigating XML Documents • XML Path Language (XPath) selects nodes from an XML document • Each expression is evaluated with respect to a context node (e.g. “child”) • Location path consists of a sequence of location steps 39 / 58
  • 40. XPath Location Steps • Axis • Specifies the tree relationship between the nodes selected by the location step and the context node • Node test • Specifies the node type and expanded-name of the nodes selected by the location step • Predicate(s) • Further refine the set of nodes selected by the location step 40 / 58
  • 41. XPath Axes Axis Ancestor Selects all ancestors (parent, grandparent, etc.) of the current node. Ancestor-or-self Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself. Attribute Selects all attributes of the current node. Child Selects all children of the current node. Descendant Selects all descendants (children, grandchildren, etc.) of the current node. Descendant-or-self Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself. 41 / 58
  • 42. XPath Axes Axis Following Selects everything in the document after the closing tag of the current node. Following-sibling Selects all siblings after the current node. Namespace Selects all namespace nodes of the current node Parent Selects the parent of the current node. Preceding Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes. Preceding-sibling Selects all siblings before the current node. Self Selects the current node. 42 / 58
  • 43. XPath Node Tests • node() is true for any node of any type • * is true for any node of the principal node type. • child::* will select all element children of the context node • attribute::* will select all attributes of the context node • comment() is true for any comment node • text() is true for any text node • processing-instruction() is true for any processing instruction 43 / 58
  • 44. XPath Predicates Restrict a node-set to select only those nodes for which some condition is true. Example: book[@genre=‘scifi’] 44 / 58
  • 45. XPath Location Paths Location step syntax: axis::nodetest[predicate] Example: /books/book/attribute::* /books/book[@genre=‘scifi’] 45 / 58
  • 46. XSLT Fundamentals • Short for Extensible Stylesheet Language Transformation • Transforms XML documents into other formats such as other XML documents, HTML or plain text • Turing-complete 46 / 58
  • 48. XSLT Processing 1. Read stylesheet file. 2. Build source tree from input XML document. 3. For each node in the source tree: 1. Process source tree node. 2. Find best-matching template in the stylesheet. 3. Evaluate the template contents. 4. Create node(s) in the result tree. 48 / 58
  • 49. Common XSLT Elements Node Description xsl:apply-templates Specifies that other matches may exist within that node. If “select” is specified, only the templates that specify a match that fits the selected node or attribute type will be applied. xsl:choose Contains xsl:when blocks and up to one xsl:otherwise block. xsl:for-each Creates a loop which repeats for every match. xsl:stylesheet Top-level element. Occurs only once in a stylesheet document. xsl:template Specifies processing templates. xsl:value-of Outputs a variable. 49 / 58
  • 50. XSLT Example XML 50 / 58 <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="books.xsl" type="text/xsl" ?> <books> <book> <title>Awesome book</title> <price>19.95</price> </book> <book> <title>Another book</title> <price>9.95</price> </book> </books>
  • 51. XSLT Example XSLT 51 / 58 <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
  • 52. XSLT Example XSLT 52 / 58 <xsl:template match="/books"> <html> <head> <title>Transforming books.xml with XSLT</title> </head> <body> <h1>Books</h1> <table> <tr> <th>Title</th> <th>Price</th> </tr> <xsl:apply-templates select="book"> <xsl:sort select="title" /> </xsl:apply-templates> </table> </body> </html> </xsl:template>
  • 53. XSLT Example XSLT 53 / 58 <xsl:template match="book"> <tr> <td> <xsl:value-of select="title"/> </td> <td> <xsl:value-of select="price"/> </td> </tr> </xsl:template>
  • 55. OpenFileDialog Control Common dialog box that allows a user to specify a filename for one or more files to open. Rendered View 55 / 58
  • 56. OpenFileDialog Control C# 56 / 58 // Show open file dialog box. OpenFileDialog openFileDialog = new OpenFileDialog { AddExtension = true, CheckFileExists = true, CheckPathExists = true, DefaultExt = ".txt", Filter = "Text files (.txt)|*.txt", ValidateNames = true }; var result = openFileDialog.ShowDialog(); if (result != true) { return; } // Open text file. using (var stream = openFileDialog.OpenFile()) { // Do something. }
  • 57. SaveFileDialog Control Common dialog that allows the user to specify a filename to save a file as. Rendered View 57 / 58
  • 58. SaveFileDialog Control C# 58 / 58 // Show save file dialog box. SaveFileDialog saveFileDialog = new SaveFileDialog { AddExtension = true, CheckPathExists = true, DefaultExt = ".txt", FileName = "TextFile", Filter = "Text files (.txt)|*.txt", ValidateNames = true }; var result = saveFileDialog.ShowDialog(); if (result != true) { return; } // Open file stream. using (var stream = saveFileDialog.OpenFile()) { // Do something. }
  • 59. Assignment #4 1. Save Map 1. Add a new MenuItem “Save As” to your MainWindow, along with a ToolBar button with tooltip. 2. Allow saving a map file by showing a Save File Dialog when the Save As command is executed. 1. Map files should be well-formed, valid XML files. 2. Each map file should contain the width and height of the map, as well as the types of all map tiles. 3. It should not be possible to save a map if there is none. 59 / 58
  • 60. Assignment #4 2. Load Map 1. Add a new MenuItem “Open” to your MainWindow, along with a ToolBar button with tooltip. 2. Add separators to both your toolbar and menu. 3. Allow loading a map file by showing an Open File Dialog when the Open command is executed. 4. Opening a corrupt or invalid XML file should result in an error message. The current map should only be discarded of the map file could be successfully opened. 60 / 58
  • 61. References • MSDN. XML Documents and Data. http://msdn.microsoft.com/en- us/library/2bcctyt8%28v=vs.110%29.aspx, May 2016. • Luttenberger. Internet Applications – Web Services Primer. Department for Computer Science, CAU Kiel, 2008. • Brandes, Eiglsperger, Lerner. GraphML Primer. http://graphml.graphdrawing.org/primer/graphml-primer.html, May 2016. • Barnes, Finch. COLLADA – Digital Asset Schema Release 1.5.0 Specification. Sony Computer Entertainment Inc., April 2008. • Clark, DeRose. XML Path Language (XPath). http://www.w3.org/TR/xpath/, November 16, 1999. • w3schools.com. XPath Axes. http://www.w3schools.com/xsl/xpath_axes.asp, May 2016. 61 / 58
  • 63. 5 Minute Review Session • What are the main benefits of using XML? • What are the three main XML processing steps? • Which XML node types do you know? • How do you properly create XmlWriter instances? • How do you read typed XML content? • What is the difference between DOM and SAX parsing? • What are the main parts of an XPath location step? • What is XSLT and how does it work? 63 / 58