c# - 使用 XmlNode.Attributes 填充文本框

标签 c# xml gridview

我有 Data.xml:

<?xml version="1.0" encoding="utf-8" ?>
<data>
<album>
    <slide title="Autum Leaves"
        description="Leaves from the fall of 1986"
        source="images/Autumn Leaves.jpg"
        thumbnail="images/Autumn Leaves_thumb.jpg" />
    <slide title="Creek"
        description="Creek in Alaska"
        source="images/Creek.jpg"
        thumbnail="images/Creek_thumb.jpg" />
</album>
</data>

我希望能够通过 GridView 编辑每个 Slide 节点的属性(添加了“选择”列。)到目前为止,我已经:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    int selectedIndex = GridView1.SelectedIndex;
    LoadXmlData(selectedIndex);
}

private void LoadXmlData(int selectedIndex)
{
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(MapPath(@"..\photo_gallery\Data.xml"));
    XmlNodeList nodelist = xmldoc.DocumentElement.ChildNodes;
    XmlNode xmlnode = nodelist.Item(selectedIndex);
    titleTextBox.Text = xmlnode.Attributes["title"].InnerText;
    descriptionTextBox.Text = xmlnode.Attributes["description"].InnerText;
    sourceTextBox.Text = xmlnode.Attributes["source"].InnerText;
    thumbTextBox.Text = xmlnode.Attributes["thumbnail"].InnerText;
}

LoadXmlData 的代码只是我的猜测 - 我不熟悉以这种方式使用 xml。我希望用户从 gridview 中选择行,然后填充一组文本框,其中每张幻灯片都归因于更新回 Data.xml 文件。

The error I'm getting is Object reference not set to an instance of an object" at the line: titleTextBox.Text = xmlnode.Attributes["@title"].InnerText;

所以我没有到达幻灯片节点的属性“标题”。感谢您提出的任何想法。

最佳答案

嗯,是的 - 给定您的 XML,xmldoc.DocumentElement.ChildNodes;语句将为您提供一个节点 - <album>节点 - 它没有任何名为 ["title"] 的属性.

你需要

  • 更改选择节点的方式; xmldoc.DocumentElement对应于<data>节点,它是 .ChildNodes集合将包括所有直接子节点 - 在本例中是唯一的 <album>节点 - 没有别的。

  • 检查是否存在! (而不仅仅是假设它有效......)

试试这个:

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(MapPath(@"..\photo_gallery\Data.xml"));

XmlNodeList nodelist = xmldoc.SelectNodes("/data/album/slide");

foreach(XmlNode xmlnode in nodelist)
{
    if(xmlnode.Attributes["title"] != null
       titleTextBox.Text = xmlnode.Attributes["title"].InnerText;

    if(xmlnode.Attributes["description"] != null
       descriptionTextBox.Text = xmlnode.Attributes["description"].InnerText;

    if(xmlnode.Attributes["source"] != null
       sourceTextBox.Text = xmlnode.Attributes["source"].InnerText;

    if(xmlnode.Attributes["thumbnail"] != null
        thumbTextBox.Text = xmlnode.Attributes["thumbnail"].InnerText;
}   

关于c# - 使用 XmlNode.Attributes 填充文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2985252/

相关文章:

c# - 传入字典的模型项的类型为 ‘mvc.Models.ModelA’,但该字典需要一个类型为“mvc.Models.ModelB”的模型项

c# - TypeDescriptor.CreateProperty 不添加属性

java - 如何使用 XSL-FO/Apache FOP 在表行中重复相同的模板

ASP.NET Gridview 服务器标记格式不正确

java - 如何使用 gridControl 组件获取替代行颜色

c# - 放弃了 gridview 固定标题

c# - Fluent FTP 无法连接到 FTP 服务器

c# - 需要数据库结构的建议(MS SQL/MySQL)

android - 更新标题文本后 NavigationView 标题中的重复值

javascript - 使用 JavaScript 检查空 XML 数据