Text boxes and Xml in C#
I just started using VS2010 and C#.
I'm trying to create an app which takes values from two textboxes and adds it to an existing xml file.
eg.
Text Box 1 Text Box 2
---------- ----------
A B
C D
E F
I want the resultant xml file to be like this.
<root>
<element>
<Entry1&g开发者_开发问答t;A</Entry1>
<Entry2>B</Entry2>
</element>
</root>
and so on...
Can this be done using C# ??
I'm unable to add the entries alternatively i.e. Entry1 should contain Text Box 1 line #1 and Entry2 Text Box 2 line #1.
Any help would be appreciated.
Thanks
You need to split the string retrieved from the text box based on the new line
like this:
string[] lines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Once you have values split for each text box, you can use System.xml.linq.xdocument class and loop through the values that you retrieve above.
Something like this:
XDocument srcTree = new XDocument(new XElement("Root",
new XElement("entry1", "textbox value1")))
You can retrieve a xml document using a linq query or save it in an xml file using the Save
method of XDocument
The below code will give you a string of XML
data from the textboxes:
private string createXmlTags(TextBox textBox1, TextBox textBox2)
{
string strXml = string.Empty;
string[] text1Val = textBox1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string[] text2Val = textBox2.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
int count = 1;
IList<XElement> testt = new List<XElement>();
for (int i = 0; i < text1Val.Count(); i++)
{
testt.Add(new XElement("Entry" + count, text1Val[i]));
while (!String.IsNullOrEmpty(text2Val[i]))
{
count = count + 1;
testt.Add(new XElement("Entry"+count,text2Val[i]));
break;
}
count = count + 1;
}
foreach (var xElement in testt)
{
strXml += xElement.ToString();
}
return strXml;
}
You can then insert the code to an existing xml document. Follow: How can I build XML in C#? and How to change XML Attribute
Read here: XDocument or XmlDocument
I will have the decency of not copying the code from there. Every basics you need to know on creating a XML doc is well explained there.
There are two options, I would personally go with XDocument.
I know there's no code in this answer but since you haven't tried anything, not even apparently searching Google (believe me, you'd find it), I'd rather point you in the right direction than "giving you the fish".
精彩评论