XML && JSON in .NET
Telerik Academy Alpha
Databases
Table of contents
-
What is XML?
-
Working with XML
-
What is JSON?
-
Working with JSON
What is XML?
What is XML?
-
XML (eXtensible Markup Language)
-
Universal language (notation) for describing structured data using text with tags
-
The data is stored together with the meta-data about it
-
Used to describe other languages (formats) for data representation
-
-
XML looks like HTML
-
Text based language, uses tags and attributes
-
What is XML?
-
Worldwide standard
-
Supported by the W3C - www.w3c.org
-
-
Independent of operating system and programming languages
<?xml version="1.0"?>
<library name=".NET Developer's Library">
<book>
<title>Professional C# 4.0 and .NET 4</title>
<author>Christian Nagel</author>
</book>
<book>
<title>Silverlight in Action</title>
<author>Pete Brown</author>
</book>
</library>
XML and HTML
-
Similarities between XML and HTML
-
Both are text based notations
-
Both use tags and attributes
-
-
Differences between XML and HTML
-
HTML is a language, and XML is a syntax for describing other languages
-
HTML describes the formatting of information, XML describes structured information
-
XML requires the documents to be well-formatted
-
Formatting
-
Well-formatted XML:
-
All tags should be closed in the correct order of nesting
-
Attributes should always be closed
-
The document should contain only one root element
-
Tag and attribute names retain certain restrictions
-
<?xml version="1.0"?>
<library name=".NET Developer's Library">
<book>
<title>Professional C# 4.0 and .NET 4</title>
<author>Christian Nagel</author>
</book>
</library>
Advantages
-
Advantages of XML:
-
XML is human readable (unlike binary formats)
-
Any kind of structured data can be stored
-
Data comes with self-describing meta-data
-
Custom XML-based languages can be developed for certain applications
-
Information can be exchanged between different systems with ease
-
Unicode is fully supported
-
Disadvantages
-
Disadvantages of XML:
-
XML data is bigger (takes more space) than in binary formats
-
More memory consumption, more network traffic, more hard-disk space
-
-
Decreased performance
-
Need of parsing / constructing the XML tags
-
-
XML is not suitable for all kinds of data
-
E.g. graphics, images and video clips
-
-
Working with XML
XML Parsers
-
XML parsers are programming libraries that make the work with XML easier
-
They serve for:
-
Extracting data from XML documents
-
Modifying existing XML documents
-
Building new XML documents
-
Validating XML documents by given schema
-
Transforming XML documents
-
XML Parsers
-
They have several working models:
-
DOM (Document Object Model)
-
Represents XML documents as a tree in the memory
-
Allows processing and modifying the document
-
-
SAX (Simple API for XML Processing)
-
Reads XML documents consequently element by element
-
Event-driven API
-
Allows analyzing the read portions at each step
-
-
StAX (Streaming API for XML)
-
Like SAX but works in "pull" mode
-
-
XML Parser in .NET
-
The DOM parser provides few important classes:
-
XmlDocument - Represents the DOM tree
-
Usually contains two elements:
-
Header part (prolog)
-
The root element of the XML document
-
-
-
XmlNode
-
Abstract base class for all nodes in a DOM tree
-
-
XmlElement
-
Represents a XML element
-
-
XmlAttribute
-
Represents an attribute of an XML tag
-
-
XML Parser in .NET - Example
XmlDocument doc = new XmlDocument();
doc.Load("library.xml");
XmlNode rootNode = doc.DocumentElement;
Console.WriteLine("Root node: {0}", rootNode.Name);
foreach (XmlAttribute atr in rootNode.Attributes)
{
Console.WriteLine("Attribute: {0}={1}", atr.Name, atr.Value);
}
var children = rootNode.ChildNodes;
Console.WriteLine("Book title = {0}", children["title"].InnerText);
Console.WriteLine("Book author = {0}", children["author"].InnerText);
Console.WriteLine("Book isbn = {0}", children["isbn"].InnerText);
The XmlNode Class
-
Working with siblings and children
-
PreviousSibling / NextSibling – returns the left / right node to the current
-
FirstChild / LastChild – returns the first / last child of the current node
-
Item (indexer [] in C#) – returns the child of the current node by its name
-
-
Working with the current node:
-
Name – returns the name of the node (element, attribute …)
-
Value – gets the node value
-
The XmlNode Class
-
Changing of the current node:
-
AppendChild(…) / PrependChild(…)
-
Inserts new child after / before all other children of the current node
-
-
InsertBefore(…) / InsertAfter(…)
-
Inserts new child before / after given inheritor
-
-
RemoveChild(…) / ReplaceChild(…)
-
Removes / replaces given child
-
-
What is JSON?
What is JSON?
-
JSON (JavaScript Object Notation) is a lightweight data format
-
Human and machine-readable
-
Based on the way to create objects in JS
-
Platform independent - can be used with any programming language
-
{
firstName: "John",
lastName: "Smith",
age: 25,
phoneNumbers: [
{ type: "home", number: "212 555-1234" },
{ type: "fax", number: "646 555-4567" }
]
}
JSON Format
-
The JSON format follows the rules of object literals in JS
-
Strings, numbers and booleans are valid JSON
-
Arrays and objects are valid JSON
-
// Strings
"this is string and is valid JSON"
// Arrays
[5, 'string', true]
// Objects
{
"firstname": "Doncho",
"lastname": "Minkov",
"occupation": "Technical Trainer"
}
Working with JSON
JSON.NET Library
-
JSON.NET is a library for parsing JSON in .NET
-
Has better performance than the JavaScriptSerializer
-
Provides LINQ-to-JSON
-
Has an out-of-the-box support for parsing between JSON and XML
-
// Serialize an object:
var jsonObj = JsonConvert.SerializeObject(obj);
// Deserialize an object:
var copy = JsonConvert.DeserializeObject<ObjType>(jsonObj);
Configuring JSON.NET
-
JSON.NET can be configured to:
-
Indent the output JSON string
-
To convert JSON to anonymous types
-
To control the casing and properties to parse
-
To skip errors
-
-
JSON.NET also supports:
-
LINQ-to-JSON
-
Direct parse between XML and JSON
-
Configuring JSON.NET
-
To indent the output string use
-
Formatting.Indented
-
-
Deserializing to anonymous types:
var json = @"{
""fname"": ""Doncho"",
""lname"": ""Minkov"",
""occupation"": ""Technical Trainer""
}";
var template = new { FName = "", LName = "", Occupation = "" };
var person = JsonConvert.DeserializeAnonymousType(json, template);
JSON.NET Parsing Objects
-
By default JSON.NET takes each Property/Field from the public interface of a class and parses it
-
This can be controlled using attributes:
-
[JsonProperty] tells the parser that Username is called user in the JSON data
-
[JsonIgnore] tells the parser to skip the property Password
-
public class User
{
[JsonProperty("user")]
public string Username { get; set; }
[JsonIgnore]
public string Password { get; set; }
}
JSON.NET Parsing Objects
-
JSON.NET has a support for LINQ-to-JSON
var jsonObj = JObject.Parse(json);
Console.WriteLine("Places in {0}:", jsonObj["name"]);
jsonObj["places"]
.Select(pl => string
.Join(", ", pl["categories"].Select(cat => cat["name"]))))
.Print();
XML to JSON and JSON to XML
-
Conversions from JSON to XML are done using two methods:
// XML to JSON
string jsonFromXml = JsonConvert.SerializeXNode(doc);
// JSON to XML
XDocument xmlFromJson = JsonConvert.DeserializeXNode(json);
Questions?
[Databases] XML && JSON in .NET
By telerikacademy
[Databases] XML && JSON in .NET
- 879