2012-08-03 82 views
2

我正在尝试xml文件中的搜索数据。如果找到,它将弹出MessageBox并显示找到的所有数据。在xml文件中搜索数据c#

这是我的代码。

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()); 
     } 

但它总是说没有找到该项目。

然后我试图做到这一点。

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); 
} 

对于这段代码,我试图把它放到列表框中。通过这样做,它说它是一个空对象。

下面是我的xml文件。

<Patient> 
     <Patient> 
     <Level>0</Level> 
     <Name>w</Name> 
     <Gender>0</Gender> 
     </Patient> 
    </Patient> 

有人可以帮我这个。

回答

1

你必须考虑你的代码是好的!但这里有一个问题:

xn["Name"].InnerText 

becase的XN代表/Patient/Patient/Name,你只需要做:

xn.InnerText 

得到它的价值。

+0

谢谢@Diego。它确实有帮助。我会投这个高。 – 2012-08-03 01:57:33

1

您是否尝试过从XMLDocument获取子节点?

因此,例如:

// 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 
    } 

看一看:

2

我个人更喜欢使用LINQ到XML,像这样:

// using System.Xml.Linq; 

var doc = XDocument.Load(@"C:\path\to\file.xml"); 
foreach (var child in doc.Descendants("Name")) 
{ 
    MessageBox.Show(child.Value); 
} 
0

除非XML文件有人叫 “姓名”,

'廉政指数= dv.Find( “名称”);'

应该是

'int index = dv.Find(“Joe”); //或其他某个名字'