0

我想做的是当我在 xmlTitle.Text(textbox) 和 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"));

    }
4

1 回答 1

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>
于 2012-08-10T15:28:44.337 回答