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"));
}
答案 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>