tags:

views:

57

answers:

1

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:

string 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);
+1  A: 

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

marc_s
This doesn't seem to work: string 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(studentID);
The Woo
Sorry, where should I put them so they can be formatted correctly?
The Woo
I've put them into the original question. :)
The Woo
exactly - edit your original question - much better choice!
marc_s
I'm pretty new to C# (if you couldn't tell already!). I have a button called: "StudentGoButton". In my form code:private void StudentGoButton_Click(object sender, EventArgs e)Where do I put your code from above?
The Woo
Inside the "_Click()" method - see my updated post
marc_s