how to select child nodes in particular xml node? - c#

I want to delete selected row and update the xml file and then load the grid view with updated data. When debugging I get null value for nodelist.
This is my xml file
<?xml version="1.0" encoding="utf-8" ?>
<PERSONES>
<person>
<name>Dilan Perera</name>
<age>22</age>
</person>
<person>
<name>Thusitha Badde</name>
<age>24</age>
</person>
</PERSONES>
Here is the button click event. The problem is I get null value for nodelist
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
string age = row.Cells[2].Text.Trim(); // i get correct value for age here
XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[#age='{0}']", age));
doc2.DocumentElement.RemoveChild(nodeList);
doc2.Save(Server.MapPath("names.xml"));
getdata();
}

The xpath query is incorrect, # means attribute, so remove # in the age check, then it will filter the element.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
string age = row.Cells[2].Text.Trim(); // i get correct value for age here
XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[age='{0}']", age));
doc2.DocumentElement.RemoveChild(nodeList);
doc2.Save(Server.MapPath("names.xml"));
getdata();
}
I have just tested this and it works.

XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode ageNode = doc2.SelectSingleNode(string.Format("//PERSONES/person/age[text() = '{0}']", age));
if (ageNode != null)
{
var personNode = ageNode.ParentNode;
doc2.DocumentElement.RemoveChild(personNode);
doc2.Save(Server.MapPath("names.xml"));
}

Related

C# how can i get all users of the XML file

I have created an xml file and there are stored my user. The problem, I only ever get the first one out. How do I manage to get all users of the XML file displayed?
private void button1_Click(object sender, EventArgs e)
{
string path = "C:\\temp\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = textBox1.Text;
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
MessageBox.Show("Created SuccesFully!");
}
private void button2_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\temp\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("/Login"))
{
MessageBox.Show(person["user"].InnerText);
}
}
I'm not sure what wasn't working for you, but this works for me. I am using //Login as the path selector. Ensure that your XML file actually has multiple users.
void Main()
{
//Create();
View();
// Output:
// User1
// User2
}
private void Create()
{
string path = "C:\\Code\\Sandbox\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = "User2";
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
Console.WriteLine("Created SuccesFully!");
}
private void View()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\Code\\Sandbox\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("//Login"))
{
Console.WriteLine(person["user"].InnerText);
}
}
Here is the generated XML. I inserted a root Logins element.
<Logins>
<Login>
<user>User1</user>
</Login>
<Login>
<user>User2</user>
</Login>
</Logins>

How to update the accessed node value it in the XML

Here I am trying to read the TID Value and I am able to read the Value(Intially it is 1)..and every time I need to increment by one and update to TID node value
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/XmlFile1.xml"));
XmlNode node = xml.SelectSingleNode("AllID/ID/TID");
int s = Convert.ToInt32( node.InnerText);
node.InnerText= s++.ToString();
xml.Save(Server.MapPath("~/XmlFile1.xml"));
}
But here it is not updating the TID value
<AllID>
<ID>
<TID>1</TID>
</ID>
</AllID>
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/XmlFile1.xml"));
XmlNode node = xml.SelectSingleNode("AllID/ID/TID");
int s = Convert.ToInt32( node.InnerText);
node.InnerText = (++s).ToString(); //Increment and make string
xml.Save(Server.MapPath("~/XmlFile1.xml"));
What about node.InnerText = s++.ToString();? I haven't tested it.

How to delete selected node from XML in C#?

I am New To C# I have problem...
I want to delete selected node from My XMl File
Here I just tried with this code but I didn't get please can any one help in that
private void btnDelete_Click(object sender, EventArgs e)
{
xdoc.Load(strFilename);
string Xpath = string.Format("root/{0}/{1}",_strProCat,_strProdType);
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);
MessageBox.Show("Deleted Successfully");
}
Here My Xml File
<root>
<product category="Soaps">
<product type="Washing">
<product name="Rin">
<Id>100</Id>
<AvailProducts>30</AvailProducts>
<Cost>20.00</Cost>
</product>
<product name="Tide">
<Id>101</Id>
<AvailProducts>30</AvailProducts>
<Cost>15.00</Cost>
</product>
</product>
</product>
</root>
Just I want to delete Node which product name="Tide"
You can simple use the below code:
private void btnDelete_Click(object sender, EventArgs e)
{
var xDoc = XDocument.Load(strFilename);
foreach (var elem in xDoc.Document.Descendants("product"))
{
foreach (var attr in elem.Attributes("name"))
{
if (attr.Value.Equals("Tide"))
elem.RemoveAll();
}
}
xDoc.Save(destinationFilename);
MessageBox.Show("Deleted Successfully");
}
Happy Coding...
Something like this should do it:
xdoc.Elements("product").Where(x=> x.Element("name").Value == "Tide").FirstOrDefault().Remove();
If you want XPath with XmlDocument then following is the way to do it..
XmlDocument xdoc = new XmlDocument();
xdoc.Load(strFilename);
string Xpath = string.Format("root/product[#category='{0}']/product[#type='{1}']/product[#name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);
Update
As per your Requirement To Remove the empty node, try following code to remove empty node as
XmlNodeList emptyElements = xdoc.SelectNodes(#"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
XmlNode nodeToBeRemoved = emptyElements[i];
nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
Now your final full flesh code will look like as
string Xpath = string.Format("root/product[#category='{0}']/product[#type='{1}']/product[#name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
XmlNodeList emptyElements = xdoc.SelectNodes(#"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
XmlNode nodeToBeRemoved = emptyElements[i];
nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
xdoc.Save(strFilename);

c# winforms Form Load ComboBox DropDownList get value from XML file

XML File:
<?xml version="1.0" encoding="utf-16"?>
<XMLFILE>
<Active>0</Active>
<Hits_Method>1</Hits_Method>
</XMLFILE>
What i'm trying to do is on Form1_Load get the value of ComboBox4 from XML File (Hits_Method) and when the program start to show me the value. i try something like this but didn't work out
// ------------------- StartUP Load
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlTextReader xreader = new XmlTextReader(xmlfile);
string comboBox4Value = xreader.GetAttribute("Hits_Method");
comboBox4.SelectedIndex = comboBox4Value;
}
Try this instead:
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);
string comboBox4Value = doc.SelectSingleNode("XMLFILE/Hits_Method").InnerText;
comboBox4.SelectedIndex = Convert.ToInt32(comboBox4Value);
}
The SelectSingleNode method extracts data based on an XPath expression. And "XMLFILE/Hits_Method" is the XPath that leads to your value.
I will use XmlDocument and XmlNode classes.
{
String sPath = "file.xml"
XmlDocument doc = new XmlDocument();
doc.Load(sPath)
XmlNode node = doc.SelectSingleNode("XMLFILE/Hits_Method");
if (node != null)
comboBox4.SelectedIndex = node.InnerText;
}

populate a tree view with an xml file

Im using .net windows form application. I have an xml file.I want to populate a tree view with data from a xml file. I am doing this using the following code.
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
//string strXPath = "languages";
string strRootNode = "Treeview Sample";
OpenFileDialog Dlg = new OpenFileDialog();
Dlg.Filter = "All files(*.*)|*.*|xml file (*.xml)|*.txt";
Dlg.CheckFileExists = true;
string xmlfilename = "";
if (Dlg.ShowDialog() == DialogResult.OK)
{
xmlfilename = Dlg.FileName;
}
// Load the XML file.
//XmlDocument dom = new XmlDocument();
//dom.Load(xmlfilename);
XmlDocument doc = new XmlDocument();
doc.Load(xmlfilename);
string rootName = doc.SelectSingleNode("/*").Name;
textBox4.Text = rootName.ToString();
//XmlNode root = dom.LastChild;
//textBox4.Text = root.Name.ToString();
// Load the XML into the TreeView.
this.treeView1.Nodes.Clear();
this.treeView1.Nodes.Add(new TreeNode(strRootNode));
TreeNode tNode = new TreeNode();
tNode = this.treeView1.Nodes[0];
XmlNodeList oNodes = doc.SelectNodes(textBox4.Text);
XmlNode xNode = oNodes.Item(0).ParentNode;
AddNode(ref xNode, ref tNode);
this.treeView1.CollapseAll();
this.treeView1.Nodes[0].Expand();
this.Cursor = System.Windows.Forms.Cursors.Default;
}
catch (Exception ex)
{
this.Cursor = System.Windows.Forms.Cursors.Default;
MessageBox.Show(ex.Message, "Error");
}
}
private void AddNode(ref XmlNode inXmlNode, ref TreeNode inTreeNode)
{
// Recursive routine to walk the XML DOM and add its nodes to a TreeView.
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(ref xNode, ref tNode);
}
}
else
{
inTreeNode.Text = inXmlNode.OuterXml.Trim();
}
}
My xml file is this:"hello.xml"
<?xml version="1.0" encoding="utf-8" ?>
<languages>
<language>
<key>abc</key>
<value>hello how ru</value>
</language>
<language>
<key>def</key>
<value>i m fine</value>
</language>
<language>
<key>ghi</key>
<value>how abt u</value>
</language>
</languages>
Now after using the above code I am able to populate the tree view. But I dont like to populate the complete xml file. I should get only till
languages
language
key
value
I don't want
abc
how are you
etc.....
I mean to say the leaf nodes. Please help me
What you don't want to add is the text content of the nodes, if I understood correctly; then, you might check the NodeType property of the XmlNode class, something like:
xNode = inXmlNode.ChildNodes[i];
if (xNode.NodeType != XmlNodeType.Text) {
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(ref xNode, ref tNode);
}

Categories