2

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

这是我的代码。

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>

任何人都可以帮我解决这个问题。

4

4 回答 4

2

我个人更喜欢像这样使用 LINQ to 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);
}
于 2012-08-03T00:32:31.840 回答
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
  }

看一下:

于 2012-08-03T00:30:01.233 回答
1

你必须考虑你的代码是好的!但问题是:

xn["Name"].InnerText

因为 xn 代表/Patient/Patient/Name,你只需要这样做:

xn.InnerText

来获得它的价值。

于 2012-08-03T00:58:37.700 回答
0

除非 xml 文件中有一个叫“名字”的人,

'int index = dv.Find("Name");'

应该

'int index = dv.Find("Joe"); //或其他名称'

于 2015-03-27T15:06:17.057 回答