使用ASP.NET和XML的可更新新闻部分

时间:2012-08-10 15:01:48

标签: asp.net xml

我尝试todo是当我在xmlTitle.Text(文本框)上放一些东西时。 xmlContent.Text(textbox)我希望我的TextXML.xml会更新,请帮忙吗?

protected void Button1_Click(object sender, EventArgs e)
    {
        XmlDocument xmlfile = new XmlDocument();
        xmlfile.Load(Server.MapPath ("~/TestXML.xml"));
        //create element
        XmlElement theNewsTag = xmlfile.CreateElement("news");
        XmlElement theTitleTag = xmlfile.CreateElement("title");
        XmlElement theContentsTag = xmlfile.CreateElement("contents");
        //create text node
        XmlText theTitleText = xmlfile.CreateTextNode(xmlTitle.Text);
        XmlText theContentsText = xmlfile.CreateTextNode(xmlContent.Text);
        //append
        theTitleTag.AppendChild(theTitleText);
        theContentsTag.AppendChild(theContentsText);

        theNewsTag.AppendChild(theTitleTag);
        theNewsTag.AppendChild(theContentsTag);
        //save
        xmlfile.DocumentElement.AppendChild(theNewsTag);
        xmlfile.Save(Server.MapPath ("~/TestXML.xml"));

    }

1 个答案:

答案 0 :(得分:0)

您的代码正在运行,为了测试它,我创建了一个名为TestXml.xml的xml

<?xml version="1.0" encoding="utf-8"?>
<Data>

</Data>

和aspx代码

     <asp:Button ID="button" runat="server" Text="Write XML"  
    onclick="button_Click" />
 <asp:TextBox  ID="xmlContent" runat="server" />
<asp:TextBox ID="xmlTitle" runat="server" />

和按钮点击事件代码

protected void button_Click(object sender, EventArgs e)
{
    XmlDocument xmlfile = new XmlDocument();
    xmlfile.Load(Server.MapPath("~/TestXML.xml"));
    //create element
    XmlElement theNewsTag = xmlfile.CreateElement("news");
    XmlElement theTitleTag = xmlfile.CreateElement("title");
    XmlElement theContentsTag = xmlfile.CreateElement("contents");
    //create text node
    XmlText theTitleText = xmlfile.CreateTextNode(xmlTitle.Text);
    XmlText theContentsText = xmlfile.CreateTextNode(xmlContent.Text);
    //append
    theTitleTag.AppendChild(theTitleText);
    theContentsTag.AppendChild(theContentsText);

    theNewsTag.AppendChild(theTitleTag);
    theNewsTag.AppendChild(theContentsTag);
    //save
    xmlfile.DocumentElement.AppendChild(theNewsTag);
    xmlfile.Save(Server.MapPath("~/TestXML.xml"));


}

我得到了以下输出

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <news>
   <title>second1</title>
   <contents>first1</contents>
 </news>
</Data>
相关问题