我有 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/