Processing XML
Introduction Last week, you saw how to get XML This week you will learn how to process it Remember the DOM from IS 360. It all works the same way from .NET because the DOM is the DOM
XML Tree Review From W3Schools.com
XML Tree Review
XML Tree Review XML documents have exactly one root element Any element can have many child elements Nodes have a type Element / attribute / text Text is stored as a child of element Attributes are a child of element
XmlDocument Class The XmlDocument class is the belongs to the System.Xml namespace. Use it to load, validate, and edit XML documents We will just read them here There are other ways to read directly from a stream Load(stream)
XmlDocument Class: Steps to Read a Document Call the constructor to create the class instance Call LoadXml() with one argument, the string containing the document You get in-memory representation of the XML document
XmlDocument Class: Reading a Document Assume that xmlString contains an XML document System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(xmlString);
Processing Documents We can extract data in different ways GetElementsByTagName() returns an XmlNodeList This is another collection So there is a Count property and an indexer GetElementById() gets an XmlNode
GetElementsByTagName() Example GetElementsByTagName takes one argument: the name of the tag and returns an XmlNodeList XmlNodeList nl; nl = xmlDoc.GetElementsByTagName("table");
The XmlNode Object It represents a node in the document A node has a type (NodeType)
The XmlNode object A node may have children (ChildNodes) A node may have content (InnerText) A node may have child XML (InnerXml) A node has a NodeType A node may have attributes (HasAttributes) If a node as attributes, then the (Attributes) collection is populated
Example, Add contents to a combo box Enumerate nodes foreach (XmlNode n in nl) { cboTables.Items.Add(n.ChildNodes[0].InnerText); }