开发者

textbox value to be stored into a new node in xml file

开发者 https://www.devze.com 2023-02-09 07:31 出处:网络
i have a textbox for users to enter their new email address. they will click the \"Update\" button and this text that they entered will then create a new entry in an existing XML file. this xml file i

i have a textbox for users to enter their new email address. they will click the "Update" button and this text that they entered will then create a new entry in an existing XML file. this xml file is used to populate 2 dropdownlist and needs to constantly update the dropdownlist with new updated entries that user entered.

i tried the following code snipper but i am weak at methods.. so please guide me

xml file: (eg i want a new builder entry)

    <?xml version="1.0" encoding="utf-8"?>
<email>
  <builderemail>
    <builder>
      <id>1</id>
      <value>builder@xyz.com</value>
    </builder>
    <builder>
      <id>2</id>
      <value>Others</value>
    </builder>
  </builderemail>
  <manageremail>
    <manager>
      <id>1</id>
      <value>manager@xyz.com</value>
    </manager>
    <manager>
      <id>2</id>
      <value>Others</value>
    </manager>
    </manageremail>
</email>

so upon this button click i call the method AddNodeToXMLFile

protected void Button1_Click(object sender, EventArgs e)
{

    AddNodeToXMLFile("~/App_Data/builderemail.xml", email);

}


public void AddNodeToXMLFile(string XmlFilePath, str开发者_如何学Going NodeNameToAddTo)
    {

        //create new instance of XmlDocument
        XmlDocument doc = new XmlDocument();

        //load from file
        doc.Load(XmlFilePath);

        //create main node
        XmlNode node = doc.CreateNode(XmlNodeType.Element, "builder", null);

        //create the nodes first child
        XmlNode ButtonName = doc.CreateElement("id");
        //set the value
        ButtonName.InnerText = "1";

        //create the nodes second child
        XmlNode url = doc.CreateElement("value");
        //set the value
        url.InnerText = "" + TextBox1.Text;

        // add childes to father
        node.AppendChild(id);
        node.AppendChild(value);

        // find the node we want to add the new node to
        XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
        // append the new node
        l[0].AppendChild(node);
        // save the file
        doc.Save(XmlFilePath);
    }

i think there is something wrong with my code..many thanks for your help


You should write:

        // add children to father
        node.AppendChild(ButtonName);
        node.AppendChild(url);

and you should check if your xmlnodelist contains any nodes to prevent exceptions:

if (l.Count > 0)
{
       // append the new node
       l[0].AppendChild(node);
 }

For the rest it looks alright to me. Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消