2009-11-01 46 views
1

我有以下的(例子):查找XML节点文本并使用我的XML文档中的ID

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

随着每个人更多的数据。我想要做的是在ac#windows应用程序窗体中,单击一个按钮,该按钮将搜索用户选择的“FullName”字段,并获取该用户条目的ID,以便我可以使用该ID填写形成。 IE:用户选择“John Smith”并按下“Go”。这将使用John Smith的数据填充表单的字段。 所以我想用2个东西,用'SelectSingleNode'?获取FullName节点的文本,然后以某种方式获取用户ID? 我的代码的其余部分正在使用XmlDocument调用。

这是我到目前为止有:

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); 
+0

这似乎是到达那里? XmlDocument fullnamefinderdoc = new XmlDocument(); fullnamefinderdoc.Load(“Data.xml”); XmlNode node = fullnamefinderdoc.SelectSingleNode(“// FullName”); – 2009-11-01 21:56:53

+0

查看我的更新日志 – 2009-11-01 22:10:23

+0

'SelectSingleNode(“// [FullName ='FullName']”);'这会搜索学生电话“FullName”...显然,您没有这样的学生... – 2009-11-01 22:14:54

回答

2

如何:

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

这应该发现学生节点“全名”,并提取“ID的字符串表示“属性,然后您可以将其转换为C#中的GUID。

从你的代码,电话是:

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

马克

+0

这似乎并不奏效: string FullName = StudentSelectStudentComboBox.Text; XmlDocument fullnamefinderdoc = new XmlDocument(); fullnamefinderdoc.Load(“Data.xml”); XmlNode node = fullnamefinderdoc.SelectSingleNode(“// [FullName ='FullName']”);如果(node!= null) {string studentID = node.Attributes [“ID”]。Value; } MessageBox.Show(studentID); – 2009-11-01 22:03:48

+0

对不起,我应该在哪里放置它们以便它们可以正确格式化? – 2009-11-01 22:07:31

+1

我已经把它们放到原来的问题中。 :) – 2009-11-01 22:08:57