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

Your code is working, to test it I create an xml with name TestXml.xml

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

</Data>

and aspx code

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

and button Click event code

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"));


}

and I got the following output

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <news>
   <title>second1</title>
   <contents>first1</contents>
 </news>
</Data>
于 2012-08-10T15:28:44.337 に答える