RingDotNetfor Ring

JSON and XML

Programs exchange data as text in a structure. JSON and XML are the two common structures; this lesson reads, searches, changes and writes both.

What you will learn#

JSON and XML in one minute#

JSON looks like Ring lists and objects:

{"name":"Ring","year":2016,"tags":["fast","small"],"author":{"first":"Ann"}}

XML is a tree of elements with attributes:

<book id="1" year="1999"><title>Learn Ring</title></book>

JSON is lighter and used by web services; XML is older and used in files and configuration.

The program#

samples/UsingDotNet/tutorials/ch01_json_xml.ring
# JSON and XML - reading, writing and searching structured data
load "dotnet.ring"

using {
	"System.Text.Json"
	"System.Xml"
}

func main

	# JSON: turn Ring data into text
	oJson = new JsonSerializer()
	? "A Ring list as JSON : " + oJson.Serialize([1,"two",[3,4]])

	# JSON: read a document you received
	cJson = '{"name":"Ring","year":2016,"tags":["fast","small"],"author":{"first":"Ann","country":"Egypt"}}'
	oDocument = new JsonDocument().Parse(cJson)
	oRoot = oDocument.RootElement
	? "The name            : " + oRoot.GetProperty("name").GetString()
	? "The year            : " + oRoot.GetProperty("year").GetInt32()
	? "Number of tags      : " + oRoot.GetProperty("tags").GetArrayLength()
	? "First tag           : " + oRoot.GetProperty("tags").Item(0).GetString()
	? "Nested property     : " + oRoot.GetProperty("author").GetProperty("first").GetString()
	oDocument.Dispose()

	# XML: a document of elements and attributes
	cXml = "<library>"
	cXml += "<book id='1' year='1999'><title>Learn Ring</title><price>25.5</price></book>"
	cXml += "<book id='2' year='2010'><title>Dot Net Basics</title><price>12</price></book>"
	cXml += "<book id='3' year='2022'><title>Ring and .NET</title><price>30</price></book>"
	cXml += "</library>"
	oDoc = new XmlDocument()
	oDoc.LoadXml(cXml)
	oBooks = oDoc.SelectNodes("//book")
	? nl + "Books in the library: " + oBooks.Count
	for nIndex = 0 to oBooks.Count - 1
		oBook = oBooks.Item(nIndex)
		? "  #" + oBook.GetAttribute("id") + " " + oBook.SelectSingleNode("title").InnerText + " (" + oBook.GetAttribute("year") + ")"
	next

	# XPath: ask questions about the document
	? "Books after 2000   : " + oDoc.SelectNodes("//book[@year > 2000]").Count
	? "Price of book 2    : " + oDoc.SelectSingleNode("//book[@id='2']/price").InnerText

	# Changing XML and saving it as text
	oNew = oDoc.CreateElement("book")
	oNew.SetAttribute([ :name = "id", :value = "4" ])
	oNew.InnerText = "A new book"
	oDoc.DocumentElement.AppendChild(oNew)
	? "After adding one   : " + oDoc.SelectNodes("//book").Count + " books"
	? "The XML now        : " + left(oDoc.OuterXml,60) + "..."
Output
A Ring list as JSON : [1,"two",[3,4]]
The name            : Ring
The year            : 2016
Number of tags      : 2
First tag           : fast
Nested property     : Ann

Books in the library: 3
  #1 Learn Ring (1999)
  #2 Dot Net Basics (2010)
  #3 Ring and .NET (2022)
Books after 2000   : 2
Price of book 2    : 12
After adding one   : 4 books
The XML now        : <library><book id="1" year="1999"><title>Learn Ring</title><...

How it works#

JSON: write#

JsonSerializer.Serialize(aList) turns a Ring list into JSON text: a list of values becomes an array, nested lists become nested arrays. (To make a JSON object from [name, value] pairs, the web library has webJson(...): see the tutorial A web service with a database.)

JSON: read#

JsonDocument.Parse(text) reads a JSON text. RootElement is the top value. From an element you:

WantCall
a property of an objectGetProperty("name")
an item of an arrayItem(0)
how many itemsGetArrayLength()
the value as text / numberGetString() / GetInt32()

Chain them to go deep: oRoot.GetProperty("author").GetProperty("first").GetString(). Dispose() frees the document when you are done.

XML: load and loop#

XmlDocument.LoadXml(text) (or @Load(file): Load is a Ring word, so the name starts with @) reads XML. SelectNodes("//book") finds all the book elements; the Count and the Item(index) of the result let you loop. For one element: GetAttribute("id") reads an attribute and InnerText the text inside.

XPath#

XPath is a small query language for XML. Examples:

XPathMeans
//bookevery book anywhere
//book[@year > 2000]the books whose year is above 2000
//book[@id='2']/pricethe price of the book with id 2

Change and save#

CreateElement("book"), SetAttribute, InnerText and AppendChild build new nodes; OuterXml is the whole document as text. Save(file) writes it to a file.

What you learned#

Exercises#

  1. Read a JSON text with an array of three numbers and print their sum.
  2. Find the cheapest book in the XML of the program with XPath and a loop.
  3. Save the changed XML to a file with oDoc.Save(cPath) and read it back.
  4. Turn the Ring list [1,[2,3],"four"] into JSON and read it back with JsonDocument.

Next#

When things go wrong

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.