Browse DevX
Sign up for e-mail newsletters from DevX


XLinq Part 1: Classes and Methods : Page 2

XLinq, one of a set of extensions to .NET languages, improves on the XML DOM in both flexibility and expressive power. This article series shows you how to take advantage of XLinq in your own applications.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Creating an XML Tree
XLinq provides a simplified yet powerful approach to creating XML elements. Using this approach, you can create all or part of your XML tree using a single line of code. This is referred to as functional construction. The following code constructs an XML block using this technique inside the Click event of a command button.

private void btnCreateXML_Click(object sender, EventArgs e) { XDocument bookStoreXml = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("Bookstore XML Example"), new XElement("bookstore", new XElement("genre", new XAttribute("name", "Fiction"), new XElement("book", new XAttribute("ISBN", "10-861003-324"), new XAttribute("Title", "A Tale of Two Cities"), new XAttribute("Price", "19.99"), new XElement("chapter", "Abstract...", new XAttribute("num", "1"), new XAttribute("name", "Introduction") ), new XElement("chapter", "Abstract...", new XAttribute("num", "2"), new XAttribute("name", "Body") ) ) ) ) ); MessageBox.Show(bookStoreXml.Xml); }

In the preceding code, a root XML element called <bookstore> acts as a container for all the child elements. To the constructor of the <bookstore> XElement, you can also supply all the child elements. This is made possible by the following constructor of the XElement that accepts a variable number of arguments through the params keyword.

public XElement(XName name, params object[] content);

Using this constructor, you can pass in a number of XElement objects that make up the content of the XML element. The supplied XElement objects are included as children of the root element. The XML output produced by the preceding example is:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <bookstore> <genre name="Fiction"> <book ISBN="10-861003-324" Title="A Tale of Two Cities" Price="19.99"> <chapter num="1" name="Introduction"> Abstract... </chapter> <chapter num="2" name="Body"> Abstract... </chapter> </book> </genre> </bookstore>

As mentioned before, the XLinq API makes working with XML elements and attributes much easier by constructing them independently of a container document. As a result, nodes are truly first-class values that can be freely passed to and returned from functions. Although the object model does provide the notion of an XmlDocument (represented by the XDocument object in XLinq), it does not require one in any shape or form to construct individual elements or attributes.

The above example used an XDocument object to insert the processing instruction at the top of the XML block. If you are constructing fragments of XML tree, you can simply use the XElement to accomplish that without going through an XDocument object.

Adding Namespaces to XML Elements
The previous example demonstrated the power of the functional construction approach, which is both nice and very extensible, because you can easily build on it to add namespaces to the XML elements. For example, you can add the namespace http://www.bookstorexml.com to the bookstore element using the following code snippet.

XNamespace nameSpace = "http://www.bookstorexml.com"; XDocument bookStoreXml = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("Bookstore XML Example"), new XElement(nameSpace + "bookstore", ---- ---- ) );

All you need to do is to append the XNamespace element to the name of the XML element when you instantiate the XElement object. This results in the following output:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <bookstore xmlns="http://mycompany.com"> ---- ---- ---- </bookstore>

Saving XML
After reading in your XML or creating some from scratch, and then manipulating it in various ways, you will probably want to output your XML. To accomplish this, you can use one of the overloaded XElement or XDocument Save() methods to output content in a variety of ways. You can save to a file, a TextWriter, or an XmlWriter. For example, to save the XDocument contents to a file named Bookstore.xml, you can write:

private void btnSaveXML_Click( object sender, EventArgs e) { XDocument bookStoreXml = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("Bookstore XML Example"), new XElement("bookstore", ---- ---- ) ); bookStoreXml.Save (@"C:\Temp\Bookstore.xml"); MessageBox.Show("Successfully saved"); }

Loading XML
You can load existing XML into an XElement object so that you can read it or manipulate it. Using the following two methods of the XElement object you can load XML data from a multitude of input sources such as a file, an XmlReader, a TextReader or a string.

  • Load—Allows you to load XML from a file, or from a XmlReader, or a TextReader object
  • Parse—Allows you to load XML from a string
As an example, the following code shows how to load XML from a file named bookstore.xml.

Figure 2. Bookstore XML Output: Here's a MessageBox showing the bookstore.xml file content.

private void btnLoadXmlFromFile_Click (object sender, EventArgs e) { XElement bookStoreXml = XElement.Load (@"C:\Temp\Bookstore.xml"); MessageBox.Show(bookStoreXml.Xml); }

Assuming that you have the bookstore.xml file loaded with XML data from the previous section, the Xml property of the XElement object produces the output in Figure 2.

Thanks for your registration, follow us on our social networks to keep up-to-date