Click here to Skip to main content
15,884,012 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to restrict the special characters like"æ"&3quƒ" from loading into XML document

[Removed duplicated posted code...]

What I have tried:

C#
try
{
	XmlDocument doc = new XmlDocument();
	doc.LoadXml(" <item><name>Progress");


	if (0==0)
	{
		XmlElement newElem = doc.CreateElement("start");
		newElem.InnerText = txtpartname.Text;
		doc.DocumentElement.AppendChild(newElem);
		XmlElement newElem1 = doc.CreateElement("starting");
		newElem1.InnerText = txtpartdesg.Text;
		doc.DocumentElement.AppendChild(newElem1);
		XmlElement newElem2 = doc.CreateElement("started");
		newElem2.InnerText = txtpartcomp.Text;
		doc.DocumentElement.AppendChild(newElem2);
		
		doc.PreserveWhitespace = true;
		doc.Save("data.xml");
	}
	else
	{
		label4.Text = "error";
	}
}
catch (Exception)
{
	labl2.Text = "Enter keyboard characters";
}
Posted
Updated 23-Aug-17 22:07pm
v2

1 solution

Add a method to strip out the unwanted characters:
C#
static char[] invalid = "æ\"&3quƒ".ToCharArray();
string StripUnwantedCharacters(string input)
{
    string output = "";

    // do work here
    if (!string.IsNullOrEmpty(input))
        output = new string(input.Where(x => !invalid.Contains(x)).ToArray());

    return output;
}

To use:
C#
newElem.InnerText = StripUnwantedCharacters(txtpartname.Text);
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900