search data in xml file c#
15,535
Solution 1
You have to consider your code is ok! But here's the problem:
xn["Name"].InnerText
Becase xn represents /Patient/Patient/Name
and you just need to do:
xn.InnerText
to get its value.
Solution 2
I personally prefer to use LINQ to XML like so:
// using System.Xml.Linq;
var doc = XDocument.Load(@"C:\path\to\file.xml");
foreach (var child in doc.Descendants("Name"))
{
MessageBox.Show(child.Value);
}
Solution 3
Have you tried just getting the childnodes from the XMLDocument?
So for example:
// Load up the document
XmlDocument formXml = new XmlDocument();
formXml.LoadXml(@"<Patient>
<Patient>
<Level>0</Level>
<Name>w</Name>
<Gender>0</Gender>
</Patient>
</Patient>");
// get the children nodes from the root
var children = formXml.ChildNodes;
// get the first or you can loop through if your xml has more children nodes
foreach (var child in children)
{
listBox21.Items.Add(child.Name); // or something similar
}
Have a look at:
- http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx
- http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/
Author by
sara brown
Updated on June 04, 2022Comments
-
sara brown almost 2 years
i am trying search data in xml file. if found, it will popup
MessageBox
and display all the data found.this is my code.
DataView dv; DataSet ds = new DataSet(); ds.ReadXml("C:\\Users\\HDAdmin\\Documents\\SliceEngine\\SliceEngine\\bin\\Debug\\saya.xml"); dv = new DataView(ds.Tables[0]); dv.Sort = "Name"; int index = dv.Find("Name"); if (index == -1) { MessageBox.Show("Item Not Found"); } else { MessageBox.Show(dv[index]["Name"].ToString()); }
but it always said the item not found.
then i tried to do this.
XmlDocument xml = new XmlDocument(); xml.Load("C:\\Users\\HDAdmin\\Documents\\SliceEngine\\SliceEngine\\bin\\Debug\\saya.xml"); XmlNodeList xnList = xml.SelectNodes("/Patient/Patient/Name"); foreach (XmlNode xn in xnList) { string name = xn["Name"].InnerText; listBox21.Items.Add(name); }
for this code, i tried to put it into the listbox. by doing this, it said that it is a null object.
below is my xml file.
<Patient> <Patient> <Level>0</Level> <Name>w</Name> <Gender>0</Gender> </Patient> </Patient>
can anybody help me with this.
-
sara brown over 11 yearsthank you @Diego. it really help. i would voting this high up.