XML in depth
XML is still everywhere — configuration files, office documents, feeds, web services. This lesson reads a document with XDocument, finds nodes with XPath, builds a new element, changes and removes nodes, and handles broken XML.
What you will learn#
- the structure of an XML document: elements, attributes, text,
- reading with
XDocument(LINQ to XML), - searching with XPath,
- creating, changing and removing elements,
- saving and reading back,
- what happens with bad XML.
The data#
<"t">class="k">library>
<"t">class="k">book "t">id="1" "t">year="1937"><"t">class="k">title>The Hobbit</"t">class="k">title><"t">class="k">price>9.5</"t">class="k">price></"t">class="k">book>
<"t">class="k">book "t">id="2" "t">year="1965"><"t">class="k">title>Dune</"t">class="k">title><"t">class="k">price>12</"t">class="k">price></"t">class="k">book>
...
</"t">class="k">library>An element has a name and can contain text and other elements; an attribute (id="1") belongs to an element. There is exactly one root element. The tutorial JSON and XML read XML in a simple way; here are the tools for real documents.
The program#
# XML in depth - reading with XDocument, searching with XPath, building and changing a document
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Xml"
"System.Xml.Linq"
}
func main
cXml = '<library><book id="1" year="1937"><title>The Hobbit</title><price>9.5</price></book><book id="2" year="1965"><title>Dune</title><price>12</price></book><book id="3" year="1984"><title>Neuromancer</title><price>8.25</price></book></library>'
# 1. XDocument (LINQ to XML) reads a text into a tree of elements. The root is the outer element.
oDocument = new XDocument().Parse(cXml)
? "1. the root element is <" + oDocument.Root.Name.ToString() + ">"
# 2. Walk the children. Elements(NULL) gives all the child elements; Attribute("x").Value and Element("y").Value read the details.
aBooks = oDocument.Root.Elements(NULL).toList()
? nl + "2. " + len(aBooks) + " books:"
nTotal = 0
for oBook in aBooks
nPrice = number(oBook.Element("price").Value)
nTotal += nPrice
? " #" + oBook.Attribute("id").Value + " " + oBook.Element("title").Value + " (" + oBook.Attribute("year").Value + ") costs " + nPrice
next
? " the total price: " + nTotal
# 3. XPath is a small language to find nodes: /library/book[@year>1950] means "the books with a year above 1950"
oXml = new XmlDocument()
oXml.LoadXml(cXml)
oFound = oXml.SelectNodes("/library/book[@year>1950]")
? nl + "3. XPath /library/book[@year>1950] finds " + oFound.Count + " books:"
for nIndex = 0 to oFound.Count - 1
? " " + oFound.Item(nIndex).SelectSingleNode("title").InnerText
next
? " the title of book 3: " + oXml.SelectSingleNode("//book[@id='3']/title").InnerText
# 4. Build a new document from scratch. An element is made with a name and, if you like, content.
oNew = (new XElement).@New([ :name = "book" ])
oNew.SetAttributeValue("id","4")
oNew.SetAttributeValue("year","1951")
oNew.Add(new XElement("title","Foundation"))
oNew.Add(new XElement("price","7.75"))
oDocument.Root.Add(oNew)
? nl + "4. after adding a book there are " + len(oDocument.Root.Elements(NULL).toList()) + " books; the new one:"
? oNew.ToString()
# 5. Change and remove
oSecond = oDocument.Root.Elements(NULL).toList()[2]
oSecond.Element("price").Value = "14"
oDocument.Root.Elements(NULL).toList()[1].Remove()
? nl + "5. book 2 now costs " + oDocument.Root.Elements(NULL).toList()[1].Element("price").Value + " and the first book is " + oDocument.Root.Elements(NULL).toList()[1].Element("title").Value
# 6. Save the text and read it back: the structure survives
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_xml.xml"])
new File().WriteAllText([ :path = cFile, :contents = oDocument.ToString() ])
oAgain = new XDocument().Parse(new File().ReadAllText(cFile))
? nl + "6. the saved file has " + len(oAgain.Root.Elements(NULL).toList()) + " books"
new File().Delete(cFile)
# 7. Bad XML raises an error: tags that are not closed
try
new XDocument().Parse("<library><book></library>")
catch
? nl + "7. bad XML: " + substr(left(cCatchError,70),nl," ")
done1. the root element is <library>
2. 3 books:
#1 The Hobbit (1937) costs 9.50
#2 Dune (1965) costs 12
#3 Neuromancer (1984) costs 8.25
the total price: 29.75
3. XPath /library/book[@year>1950] finds 2 books:
Dune
Neuromancer
the title of book 3: Neuromancer
4. after adding a book there are 4 books; the new one:
<book id="4" year="1951">
<title>Foundation</title>
<price>7.75</price>
</book>
5. book 2 now costs 14 and the first book is Dune
6. the saved file has 3 books
7. bad XML: DotNet Error: System.Xml.XmlException: The 'book' start tag on line 1This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
XDocument#
new XDocument().Parse(text) builds the tree. oDocument.Root is the root element. Elements(NULL) gives all child elements (NULL because the method has other forms, see Core concepts), and .toList() makes a Ring list. For each element Attribute("year").Value reads an attribute and Element("title").Value the text of a child. The values are always texts: convert with number() when you need a number (step 2 adds the prices).
XPath#
XPath describes a path through the tree:
| XPath | Finds |
|---|---|
/library/book | all books under the root |
//book | every book at any depth |
/library/book[@year>1950] | books with a year attribute above 1950 |
//book[@id='3']/title | the title of book 3 |
It is part of XmlDocument (SelectNodes, SelectSingleNode). One short expression replaces loops with ifs.
Creating and changing#
An element is created with a name and optional content: dnNew("XElement",[ :name = "title", :content = "Foundation" ]). SetAttributeValue("id","4") adds an attribute, Add(child) appends a child. To change a text assign element.Value; Remove() deletes an element from its parent. ToString() gives indented XML text, which File.WriteAllText can save.
Bad XML#
XML is strict: every tag must be closed and tags must nest. Parse raises an error with the line and the problem (step 7). Always parse data that comes from outside inside try / catch (the tutorial When things go wrong).
Text that you put into XML must be escaped (< → <, & → &). When you build elements with XElement this is done for you. Never build XML by adding strings together.
What you learned#
- elements, attributes, the root,
XDocument:Root,Elements,Element,Attribute,- XPath with
XmlDocument, - building, changing and removing,
- errors in bad XML.
Exercises#
- Write the books as a table: title, year and price in columns (the tutorial Tabular data).
- Use XPath to find the books cheaper than 10.
- Add a
<tags>element with several<tag>children to each book. - Convert the list of books to JSON (the tutorial JSON and XML) and back.