how to fetch node elements from XML file by using xpath query, - c#

i want to fetch elements through search pattern like if i type "an" then i want all elements which have "an" example =man, animal, fan, pant
this is my code here i use foreach loop to display all search elements but i don't want to use foreach loop just i want to fetch all the list directly form xpath query please help me out its very impotent for me
private void Search2_Click_1(object sender, EventArgs e)
{
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("/students/student/s_name" );
string ha = search.Text;
if (listbox11.Text == "Name")
foreach(XmlNode node in nodes)
{
if(System.Text.RegularExpressions.Regex.IsMatch(node.InnerText,ha))
{
listBox1.Text += node.InnerText + "\r\n";
}
}
}

Use this
private void Search2_Click_1(object sender, EventArgs e)
{
string ha = search.Text;
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("/students/student/[contains(s_name,ha)]");
}

**The code which i write is simple, xpath query will fetch only related elements nodes but if you want to print then use foreach loop **
private void Search2_Click_1(object sender, EventArgs e)
{
string ha = search.Text;
if (listbox11.Text == "Name")
{
listBox1.Text = "";
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("//s_name[descendant-or-self::*[contains(.,'" + ha + "')]]");
foreach (XmlNode node in nodes)
{
listBox1.Text += node.InnerText + "\r\n";
}
}
}

Related

C# get folderpath from TreeListNode in treeList devexpress

I use XtratreeList with fileExplorerAssistant. I have a problem when I want to get the path of the selected folder from treelist. Or I have a problem in getting the folder path from TreeListNode. Please help me.
My code is :
private void frmMovieAddAuto_Load(object sender, EventArgs e)
{
// Scan for all partitions
System.IO.DriveInfo[] driveList = System.IO.DriveInfo.GetDrives();
foreach (var drive in driveList)
{
// Select only logical fixed partitions
if (drive.DriveType == System.IO.DriveType.Fixed && drive.IsReady)
{
// Add each drive as a root node
treeListExtension1.RootNodes.Add(new PathNode(drive.RootDirectory.ToString()));
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TreeListColumn columnname;
columnname = treeList1.Columns[0];
columnname.Caption = "Folder Name";
List<TreeListNode> nodes = treeList1.GetNodeList();
foreach (TreeListNode node in nodes)
{
if (node.Checked == true)
{
DirectoryInfo di = new DirectoryInfo(node.GetValue(columnname).ToString());
foreach (FileInfo fi in di.GetFiles("*.avi;*.mpg;*.mpeg;*.mp4;*.mkv;*.divx;*.AVI;*.MPG;*.MPEG;*.MP4;*.MKV;*.DIVX", SearchOption.AllDirectories))
{
//do something
}
}
}
}
In this code:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
// Get the node that is currently focused (selected) in the TreeList
TreeListNode focusedNode = treeList1.FocusedNode;
// Get the column that contains the folder path
TreeListColumn folderPathColumn = treeList1.Columns[0];
// Get the value of the folder path column from the focused node
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
if(focusedNode.Checked == true)
{
pathfolderList.Add(folderPath);
}
}
In this line code:
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
It gives this error:
'Object reference not set to an instance of an object.'
Your question is how to get the full path of a DevExpress.XtraTreeList.Nodes.TreeListNode. This requires traversing the DisplayText from the selected node up to its root, When this collection is reversed and combined, the result is the full path.
foreach (var node in treeList1.GetNodeList())
{
List<string> builder = new List<string>();
TreeListNode traverse = node;
// This adds the display text from the leaf to the root.
while(traverse != null)
{
builder.Add(traverse.GetDisplayText(0));
traverse = traverse.ParentNode;
}
// What we want is the root to the leaf, so reverse the list.
builder.Reverse();
// Now combine into a path.
var path = Path.Combine(builder.ToArray());
Debug.WriteLine(path);
}
You might also find the DevExpress documentation helpful (their approach is slightly different).

C# access to TreeNode parameter

Here is code:
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" + DirSize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)"+ directoryInfo.CreationTime);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)"));
return directoryNode;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = "a";
textBox1.Text = selectedNodeText;
}
I need to access directoryInfo.CreationTime from TreeNode and display it in treeView1_AfterSelect text.Box1 but I can't find right way.
You can use the Tag property of TreeNode to put the value there and then access it in the event :
directoryNode.Tag = directoryInfo;
and then in event you can access it :
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = e.Node.Tag as DirectoryInfo;
var time = directoryinfo.CreationTime;
}
or:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = treeView1.SelectedNode.Tag as DirectoryInfo;
var creationTime = drInfo.CreationTime;
}
Hope it helps!
Tree nodes expose the Tag property that is used to store and retrieve a custom information under nodes. It can even hold a reference to a complex structure.
https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag(v=vs.110).aspx

Get the value of an attribute from webbrowser1

I have the following code which extracts all URLS within Google's search results:
private void button1_Click(object sender, EventArgs e)
{
HtmlElementCollection a = webBrowser1.Document.GetElementsByTagName("a");
foreach (HtmlElement b in a)
{
string item = b.GetAttribute("href");
if (item.Contains("url?q="))
{
listBox1.Items.Add(item);
}
}
}
However I need this to be more specific.
Google's Chrome element inspector has this and I need to access the URL in this element:
<cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>
The class is "_Rm", its in a 'cite' tag, and I need that URL ONLY.
Find html element with specified 'class' and 'tag' values. Then retrieve an url from InnerHtml.
HtmlElement FindHtmlElement(string tag, Predicate<HtmlElement> predicate)
{
try
{
var elements = webBrowser1.Document.GetElementsByTagName(tag);
foreach (HtmlElement element in elements)
{
if (predicate(element))
{
return element;
}
}
}
catch (Exception ex)
{
//Log.Error("Error on finding html element on {0}. Exception: {1}", _webBrowserBot.Url.ToString(), ex.Message);
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
// search for <cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>
var element = FindHtmlElement("cite", (h) =>
{
return h.GetAttribute("class") == "_Rm";
});
string url = "";
if (element != null)
{
// retrieve url only
int ix = element.InnerHtml.IndexOf("-<b>");
if (ix > 0)
url = element.InnerHtml.Remove(ix);
// url obtained
//...
}
}

My for statement isn't working properly

I have tried so much different iterations of the for loops and all of them dont work properly or work only halfway. So I cant figure it out.
Heres my form:
So what its supposed to do is create a folder for each node in the treeview (Named FolderTV) when I click the Create folders button.
What it currently does is only creates the New_Mod folder and the Data folder nothing else. I want it to create a folder for every node and subnode. For example it would create the New_Mod folder and then within that folder It will create the Data, Models, and Textures folder and within the Data folder it would create a Scripts folder.
Here's my code for that button:
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i <= FoldersTV.Nodes.Count; i++)
{
FoldersTV.SelectedNode = FoldersTV.TopNode;
MessageBox.Show("Current Node: " + FoldersTV.SelectedNode.Text.ToString());
Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString());
for (int x = 0; x <= FoldersTV.Nodes.Count; x++)
{
TreeNode nextNode = FoldersTV.SelectedNode.NextVisibleNode;
MessageBox.Show("Next Node: " + nextNode.Text.ToString());
Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString() + "\\" + nextNode.Text.ToString());
x++;
}
i++;
}
}
Try this (untested) recursive solution and try to understand it first ;)
private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {
foreach(var node in nodes) {
// string dir = path + "\\" + node.Text;
string dir = Path.Combine(path, node.Text);
Directory.CreateDirectory(dir);
CreateDirs(dir, node.Nodes);
}
}
private void button3_Click(object sender, EventArgs e) {
CreateDirs(SEAppdata, FoldersTV.Nodes);
}
EDIT: Version with few debug printouts:
// using System.Diagnostics;
private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {
// iterate through each node (use the variable `node`!)
foreach(var node in nodes) {
// combine the path with node.Text
string dir = Path.Combine(path, node.Text);
// create the directory + debug printout
Debug.WriteLine("CreateDirectory({0})", dir);
Directory.CreateDirectory(dir);
// recursion (create sub-dirs for all sub-nodes)
CreateDirs(dir, node.Nodes);
}
}
See: System.Diagnostics.Debug.WriteLine

Read XML and add it to a listView with multi columns

how can i add subItems into my listView with 3 columns?
it only adds items to the first column
//Read XML
private void button3_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument loadDoc = new System.Xml.XmlDocument();
loadDoc.Load(Application.StartupPath + "\\Computers.xml");
foreach (System.Xml.XmlNode nameNode in loadDoc.SelectNodes("/Computers/Item"))
{
listView1.Items.Add(nameNode.Attributes["name"].InnerText); ;
}
foreach (System.Xml.XmlNode ipNode in loadDoc.SelectNodes("/Computers/Item"))
{
listView1.Items.Add(ipNode.Attributes["ip"].InnerText); ;
}
foreach (System.Xml.XmlNode macNode in loadDoc.SelectNodes("/Computers/Item"))
{
listView1.Items.Add(macNode.Attributes["mac"].InnerText); ;
}
}
thank you in advance!
listView1.Items.Add(nameNode.Attributes["name"].InnerText);
listView1.Items[listview1.Items.Count-1].Subitems.Add(ipNode.Attributes["ip"].InnerText);
listView1.Items[listview1.Items.Count-1].Subitems.Add(macNode.Attributes["mac"].InnerText); ;

Categories