Introduction
This article is intended to show you how XPath queries have made programmers’ life easier regarding XML data manipulation. XML applications have many varieties; from simple client-side and server-side applications to web services over the Internet. However, one particular fact never changes; Data change dynamically and constantly. In this simple and short newcomer's project we will search for data within an XML document using two different XPath queries. Also, we will add a method to replace current information with new information. Since this is my first article regarding Microsoft C# and XML there might be some points which, need modification or improvement so please contact me to share your ideas or any suggestions you may have. Personally, I like to write every project from scratch! in this case, read the following steps:
Create a new project:
1 - Launch Visual Studio.Net IDE and select “Windows Application” under Visual C# Projects. Of course, you can select "Console Application" only it requires you to modify part of the source code.
2 - The controls, which, we would need are TreeView , Edit-Box, List-Box, Button & Label controls.
3 - First, let's consider the Nampespaces, which are necessary to include:
3 -1 ) System.Xml
3-2 ) System.Xml.Xpath
3-3 ) System.Text
3-4 ) System.Collections.Specialized //Was used for holding Node paths and Node attributes but I removed them to make the code smaller
Note: Please ignore System.Collections.Specialized.
4 - Define a sturcutre as below:
struct TXN
{
public TreeNode nnode;
public XmlNode xnode;
public TXN(TreeNode nnode, XmlNode xnode)
{
this.nnode = nnode;
this.xnode = xnode;
}
}
5 - Also, I did name the controls as:
private System.Winodws.Forms.GroupBox treeGroupBox;
private System.Winodws.Forms.TreeView treeXmlBody;
private System.Winodws.Forms.Button btnOpenXml;
private System.Winodws.Forms.Button btnReplace;
private System.Winodws.Forms.Button btnClose;
private System.Winodws.Forms.Label lblItem; private System.Winodws.Forms.Label lblPath;
private System.Winodws.Forms.ListBox listBoxPaths;
private System.Winodws.Forms.TextBox txtItem;
private System.Winodws.Forms.Button btnSearch;
private System.Winodws.Forms.TextBox txtReplace;
Some public variables too:
public string sXPathQuery; public string sPath;
also:
private XmlDocument xdoc;
- For more information please refer to comments or contact me. Once again, thanks for reading the article.