2012-08-03 63 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」); //或其他某個名字'