代码之家  ›  专栏  ›  技术社区  ›  Doug

用XmlNode.Attributes填充文本框

  •  2
  • Doug  · 技术社区  · 16 年前

    我有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(添加了“Select”列)编辑每个幻灯片节点的属性,到目前为止,我已经:

    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文件。

    我得到的错误是对象引用没有设置为一个对象的实例“在:titleTextBox.Text=xmlnode.Attributes[“@title”].InnerText;

    所以我没有到达幻灯片节点的属性“title”。谢谢你的建议。

    2 回复  |  直到 16 年前
        1
  •  3
  •   marc_s MisterSmith    16 年前

    是的-考虑到你的XML xmldoc.DocumentElement.ChildNodes; 语句只会给你一个节点 <album> ["title"]

    你需要

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

    • 检查是否存在(不只是假设它有效……)

    试试这个:

    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;
    }   
    
        2
  •  0
  •   abatishchev Karl Johan    16 年前

    @title 是对属性的XPath调用,即。 "//slide['@title']"

    XmlNode.Attributes 仅按名称保存属性- title node.Attributes["title"]