开发者

Finding XML node text and using its ID

I have the following (example) of my xml document:

<Students>
    <Student ID = *GUID NUMBER*>
    <FullName>John Smith</FullName>
    <Address>123 Fake St</Address>
    </Student>
    <Student ID = *GUID NUMBER*>
    <FullName>Henry Doe</FullName>
    <Address>321 Whatever Lane</Address>

With more data in each person. What I want to do is in a c# windows app form, click a button that will search for the 'FullName' field that the user has selected, and get the ID of that user entry, so that I can use that ID to fill a form. IE: User selects 'John Smith' and presses 'Go'. This will populate the fields of the form with John Smith's data. So I am thinking of 2 things, using 'SelectSingleNode'? to get the text of the FullName node, and then somehow of getting the users ID? The rest of my code is using XmlDocument calls.

This is what I have so far:

stri开发者_运维百科ng FullName = StudentSelectStudentComboBox.Text;
XmlDocument fullnamefinderdoc = new XmlDocument();
fullnamefinderdoc.Load("Data.xml");
XmlNode node = fullnamefinderdoc.SelectSingleNode("//[FullName='FullName']");
if (node != null)
{ string studentID = node.Attributes["ID"].Value; }
MessageBox.Show("Student ID is: " + studentID);


How about this:

public string FindStudentID(string fullName)
{
   string result = string.Empty;

   XmlDocument doc = new XmlDocument();
   doc.Load(@"your-xml-file-name.xml");

   string xpath = string.Format("/Students/Student[FullName='{0}']", fullName);
   XmlNode node = doc.SelectSingleNode(xpath);

   if (node != null)  // we found John Smith
   {
      result = node.Attributes["ID"].Value;
   }

   return result;
}

That should find the student node for "fullName", and extract the string representation of the "ID" attribute, which you can then cast to a GUID in C#.

From your code, call is with:

private void StudentGoButton_Click(object sender, EventArgs e) 
{
    string myStudentID = FindStudentID(StudentSelectStudentComboBox.Text);
}

Marc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜