2011-02-08 57 views
0

我有一个用于输入新的电子邮件地址的文本框。他们将点击“更新”按钮,然后他们输入的文本将在现有的XML文件中创建一个新条目。此xml文件用于填充2个下拉列表,并需要不断用用户输入的新更新条目更新下拉列表。将文本框的值存储到xml文件中的新节点中

我尝试下面的代码剪断,但我的方法弱..所以请指导我

xml文件:(例如:我希望有一个新的构建器条目)

<?xml version="1.0" encoding="utf-8"?> 
<email> 
    <builderemail> 
    <builder> 
     <id>1</id> 
     <value>[email protected]</value> 
    </builder> 
    <builder> 
     <id>2</id> 
     <value>Others</value> 
    </builder> 
    </builderemail> 
    <manageremail> 
    <manager> 
     <id>1</id> 
     <value>[email protected]</value> 
    </manager> 
    <manager> 
     <id>2</id> 
     <value>Others</value> 
    </manager> 
    </manageremail> 
</email> 

所以在这个按钮点击我所说的方法AddNodeToXMLFile

protected void Button1_Click(object sender, EventArgs e) 
{ 

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

} 


public void AddNodeToXMLFile(string XmlFilePath, string 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); 
    } 

我觉得有什么不对我code..many感谢您的帮助

回答

0

你应该写:

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

,你应该检查你的XmlNodeList中包含的任何节点,以防止例外:

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

对于它看起来好了给我休息。祝你好运!

+0

谢谢你:D解决了我的查询 – jeremychan 2011-02-08 09:03:52

相关问题