Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2010-01-12
Today I had to be able to query XML files using XPath and view the result clean and structured. Doing this from within Visual Basic is very easy, so making a tool was an easy option. This is the user interface:
The top pane is used for writing XPath queries. Below, there are three panes. One displays the result as a tree structure, the next displays the attributes of the selected node in the tree view and the last display the source of the selected node.
This is the Click event of the query button:
Private Sub DoExecute(ByVal XPath As String) 'Store the last executed query in case the user wants to refresh the query. Me.LastExecutedQuery = XPath 'Clear the output textbox. txtOutput.Text = "" 'Clear the elements tree view. tvElements.Nodes.Clear() 'Clear the attribute list. lvAttributes.Items.Clear() If XPath.Trim() = "" Then 'If no query is sent in, display the root element. 'Display it in the tree (using a custom function not shown here). Me.AddNode(Dom.DocumentElement, tvElements.Nodes) 'This is the status bar of the window. lblResult.Text = "Elements in result: 1" Else 'The query might fail. Try Dim Result As Xml.XmlNodeList = Dom.DocumentElement.SelectNodes(XPath) If Result Is Nothing Then lblResult.Text = "Elements in result: 0" Else If Result.Count = 0 Then lblResult.Text = "Elements in result: 0" Else Me.ResultList = Result lblResult.Text = "Elements in result: " & Result.Count.ToString() Dim ResultNode As TreeNode = tvElements.Nodes.Add(XPath.Trim()) ResultNode.Tag = "Query" ResultNode.ImageIndex = 3 ResultNode.SelectedImageIndex = 3 'Populate the tree structure (using a custom function not shown here). tvElements.BeginUpdate() For Each Xn As Xml.XmlNode In Result Me.AddNode(Xn, ResultNode.Nodes) Next tvElements.EndUpdate() 'Expand the root node that contains the result. ResultNode.Expand() End If End If Catch ex As Exception 'If the query failed, extract the reason from the exception and display it. lblResult.Text = "Elements in result: [Error]" txtOutput.Text = "XPath failed." & ControlChars.CrLf & ControlChars.CrLf & ex.Message End Try End If 'Select the first node. Other panes will be updated in the AfterSelect event of the treeview. If tvElements.Nodes.Count > 0 Then tvElements.SelectedNode = tvElements.Nodes(0) tvElements.SelectedNode.EnsureVisible() End If End Sub
To use this, just open an XML file and click away in the tree view. You can also write XPath queries to browse a subset of the data. If you want to download this early version, the exe file (.NET Framework 3.5) is located here Since 17/1 2010, the program is can be downloaded from here.
Categories: Microsoft .NET
Tags: XQT
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply