Welcome!

PowerBuilder Authors: Dan Joe Barry, Carmen Gonzalez, Ian Thain, Yakov Werde, Paul Slater

Related Topics: PowerBuilder

PowerBuilder: Article

Using .NET XML API in PowerBuilder

Exploring the .NET framework

XML is becoming the standard for data exchange. More and more software products and technologies are being built on top of it. Even the newest buzz word in Internet programming- AJAX - is related to XML. The good news is that .NET framework provides a very powerful API for manipulating XML, and you, as a PowerBuilder developer, can leverage on that API through the .NET interoperability feature released in PowerBuilder 11.

In this article, I will walk you through a code sample, showing how to:

  • Read and write XML files,
  • Traverse a XML DOM tree, and
  • Query XML data using XPath.
The code sample, which is a .NET Windows Forms target, contains three PBLs: usexml.pbl, netxml.pbl, and netui.pbl. The majority of the code is in usexml.pbl, while netxml,pbl and netui.pbl provide some utilities for XML and GUI effects, respectively. Figure 1 shows the main window of the sample.

Writing XML files
Clicking on the "Writing XML" button will open up the "Writing XML" window, as shown in Figure 2. The window contains a DataWindow and two buttons. When you click on the "Save as XML" button, a GetSaveFileName dialog will pop up prompting you to specify a file name and then save the DataWindow to the file in XML format (see Listing 1). The root node - CustomerDetails - contains a number of Customer nodes, which, in turn, contain FirstName, LastName, CompanyName, and PhoneNumber nodes.

Now let's examine the code. Listing 2 is the script of the clicked event of the "Save as XML" button. The script opens up a GetSaveFileName dialog. If a file name is specified correctly, it calls the saveXmlFile() function (Listing 3).

The function creates an instance of the .NET XmlWriter class and writes a CustomerDetails node (the root node). Then for each row of the DataWindow, it writes a Customer, then under that, writes four nodes for the FirstName, LastName, CompanyName, and PhoneNumber, respectively.

The XmlWriter class is an abstract class. The real type of the object doing the job is actually XmlTextWriter, which provides a fast, non-cached, forward-only way of generating streams or files containing XML data. The major methods and properties of the class include Close, Flush, Formatting, WriteAttribues, WriteAttributeString, WriteComment, WriteElementString, WriteElementString, WriteEndAttribute, WriteEndDocument, WriteState, and WriteStartDocument. For details, please refer to MSDN.

Reading XML files
The w_readxml window (Figure 3) demonstrates how to read an XML file and populate a TreeView with the elements of the XML file.

The clicked event of the "Read XML" button calls the readXmlFile() function, which uses the .NET XmlTextReader class to read the elements from an XML file. The code of the readXmlFile() function is shown in Listing 4.

The function creates an instance of the XmlTextReader class, which provides forward-only, read-only access to a stream of XML data. The XmlTextReader.NodeType property indicates the type of the current node, which can be element, attribute, text, CDATA, comment, and so on. An element node can have attributes. The XmlTextReader.Name and XmlTextReader.Value properties are for getting the name and value of the current node. Please refer to MSDN for details.

In order to insert the XML nodes into the TreeView, the function maintains an array of TreeViewItem handles and named handles, representing the current tree branch, which allows it to traverse back from the leaf node to the root node.

If the element has attributes, it adds an node for each attribute under the element node. If the element has attributes, it adds a node for each attribute node under the element node. If the current node is text, it inserts a text node under the current element node.

Traversing XML DOM
The code of the readXMLFile and the populate Tree functions are shown in Listing 5 and 6. If you want to load an XML file into memory and then manipulate the DOM tree, the XmlDocument class is more appropriate for that purpose. The w_dom window, which looks very similar to w_readxml, shows how to use this class.

The main code is in the readXmlFile function of this window object. The function creates an instance of the .NET XmlDocument class, creates an instance of the XmlTextReader class, and loads the XML file into memory through the XmlTextReader object. With the DOM tree we can populate the TreeView pretty easily by calling the recursive function, populateTree.

Notice that we pass an n_xmlElement object to the populateTree function rather than passing a .NET XmlElement object directly. This is because PowerBuilder 11 doesn't allow you to use a .NET type as a parameter of a function. To overcome this limitation, the n_xmlElement NVO is defined to wrap an instance of XmlElement.

The code of the readXMLFile and the populateTree functions are shown in Listing 5 and 6. For each child node of the given XmlElement, the function adds it to the TreeView. If a child node is an element, the populateTree is called recursively to add the child node to the TreeView.

With the XML DOM in hand, you can add new nodes, remove nodes, or modify nodes of the DOM tree. You can also save the DOM tree to a file.

Querying XML data using XPath
The XmlDocument class has certain limitations. First of all, the entire document needs to be loaded into memory. So the class is not suitable for huge XML files. The XPathDocument and XPathNavigator classes are intended to address this, as they allow you to process XML data without loading the entire DOM tree.

The w_xpath window (Figure 4) demonstrates how to use XPathDocument and XPathNavigator classes.

In this screen shot, we choose the XML file generated with the w_writexml window and then ask the program to list all LastNames with the XPath expression, CustomerDetails/Customer/LastName.

In fact, you can choose any XML file and use appropriate XPath expression to the process the data.

The code is in the clicked event of the Search button (Listing 7). We first create an instance of XpathDocument, then create an XPathNavigator instance by calling the XpathDocument.CreateNavigator method, then get an XpathNodeIterator with the specified XPath expression. With the XpathNodeIterator in hand, we can iterate through the items and add them to the ListBox.

Further Readings on .NET XML APIs
I hope I have shown you the power of the .NET XML API. The .NET XML API allows you to do many other things besides those that are shown in the sample. To explore how to use the API, I highly recommend the following articles in addition to the MSDN site.

1)  XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation
(http://msdn.microsoft.com/msdnmag/issues/01/01/xml/).

2)  The ".NET XML Best Practices" series:
- Part I: Choosing an XML API (http://support.softartisans.com/kbview.aspx?ID=673).
- Part II: Reading XML Documents (http://support.softartisans.com/kbview.aspx?ID=674)
- Part III: Writing XML Documents (http://support.softartisans.com/kbview.aspx?ID=675)

Some GUI Effects
You may have already noticed that the shape of the "Write XML" button on the main window is oval. This is achieved by calling the f_makeOval function object.

Trying to resize the four sub-windows, you will see the controls anchoring to the borders of the window quite nicely. It is the f_anchorControl function object that does the trick. Please figure out how these two functions work by your own by examining the downloadable sample code.

Conclusion
The .NET interoperability feature of PowerBuilder 11 makes the .NET framework widely open to you. Explore the. NET framework and you will find many things that you can leverage on. For example, the System.Collections, System.IO, System.NET, and System.Security.Cryptography namespaces. There are still some limitations in .NET interoperability in PowerBuilder 11 (e.g., the code for calling .NET classes has to be inside "if defined pbdotnet/#end if" code blocks, and .NET classes can't be used as parameters and return types of functions). We will gradually remove the limitations and enhance the .NET interoperability feature in future releases.

More Stories By Xue-song Wu

Xue-song Wu, a staff software engineer in Sybase Asia Development Center, Singapore, team leader of PowerBuilder Virtual Machine and Compiler team.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.