将XMLDocument子节点加载到文本框?

时间:2017-02-15 20:40:03

标签: c# xml xpath

我想将一些XML子节点加载到特定的文本框中,但只能通过创建XmlDocument子节点的XMLNodeList,并通过它们作为列表迭代并通过索引调用它们来查找如何执行此操作的示例。有没有办法通过标记名称在XMLDocument中获取特定的子节点?

//my xml file
<?xml version="1.0" encoding="UTF-8"?>
<Textboxes>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
</Textboxes>

    //c# method to load textboxes by child node names
    private void LoadTextboxes()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Application.StartupPath + "\\Saved.xml");

        txtFirstName.Text = doc.??? // get <FirstName>
        txtLastName.Text = doc.??? // get <LastName>   
    }

1 个答案:

答案 0 :(得分:1)

鉴于您提供的样本,这样的事情应该有效:

private static void LoadTextboxes()
{
    XmlDocument doc = new XmlDocument();
    doc.Load(Application.StartupPath + @"\Saved.xml");
    txtFirstName.Text = doc.LastChild.SelectSingleNode("FirstName").LastChild.Value; // get <FirstName>
    txtLastName.Text = doc.LastChild.SelectSingleNode("LastName").LastChild.Value; // get <LastName>   
}