Skip to main content
 首页 » 编程设计

C# 写入特定的 XML 节点

2024年02月24日22sharpest

我有一个格式如下的 xml 数据库:

<Students> 
 <Student ID= *GUID NUMBER*> 
  <FullName>John Smith</FullName> 
  <Address>Blah blah blah</Address> 
  and so on... 
 <Student ID= *GUID NUMBER*> 
  <FullName>Joe Blow</FullName> 
  <Address>Blah Blah</Address> 
  and so on... 

我有一个组合框,它将从此 xml 数据中进行选择,以在其下拉列表中显示 FullName。现在我需要做的是根据在组合框中选择的 FullName 更新其他字段并将节点添加到所选学生,然后按下另一个按钮 - “提交”。

请您参考如下方法:

要选择特定的Student 节点,您可以:

XmlDocument xml = new XmlDocument(); 
xml.LoadXml("<Students>...."); // or xml.Load("yourfile.xml"); 
XmlElement student = xml.SelectSingleNode( 
    String.Format("//Student[@ID='{0}']", 
                  yourcombo.SelectedItem.Value)) as XmlElement; 
if(student != null) 
{ 
    XmlElement another = xml.CreateElement("another"); 
    another.InnerText = "Value"; 
    student.AppendChild(another); 
 
    // do other stuff 
}