edit XML from textbox on ASP.NET page
I have an XML file XMLData.xml
开发者_开发技巧<pdata>
<name>John</name>
<age>36</age>
</pdata>
I want to be able to overwrite the "name" and "age" node from a textbox control on an ASP.NET page. I have found a lot of info on how to do this with a datagrid but I need to use a textbox for each node.
Any help would be awesome.
I'm not 100% sure I understand your question but...
It seems like if you loaded the file into an XMLDocument, then used XPath to select the XMLNode objects you wanted to overwrite, and set their inner text properties, then write the xml document back out that would do the trick.
XMLDocument doc = new XMLDocument();
doc.load("filepath");
XmlNode root = doc.DocumentElement;
XmlNode name = root.SelectSingleNode("/pdata/name");
name.InnerText = TextBox.Value;
doc.WriteTo(new XmlWriter());
Give this a try:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Height="251px" TextMode="MultiLine" Width="510px">
</asp:TextBox>
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
string xml = "<root><name>aaa</name></root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
StringBuilder sb = new StringBuilder ();
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(sb, settings);
doc.WriteTo(writer);
writer.Close();
this.TextBox1.Text = sb.ToString();
}
Linq to XML would make it much simpler
string path = Path.Combine(Server.MapPath("."), "App_Data\\XMLData.xml");
XDocument doc = XDocument.Load(path);
XElement myData = doc.Elements("pdata").Single();
myData.ReplaceNodes(
new XElement("name", NameText.Text.Trim()),
new XElement("age", AgeText.Text.Trim())
);
doc.Save(path);
精彩评论