How to remove special characters from a XML

做~自己de王妃 提交于 2019-12-11 04:18:16

问题


I have an xml file. I want to remove all of the special characters in it using C#.

The special characters include:

  1. +
  2. -
  3. /
  4. _

etc.


回答1:


Step 1 : Load Xml file to string

public string ReadFileToString(string filePath)
{
 StreamReader streamReader = new StreamReader(filePath);
 string text = streamReader.ReadToEnd();
 streamReader.Close();
 return text;
}

Setp 2: Remove all the occurance of special char by using the function

public static string RemoveSpecialCharacters(string str)
{
    //change regular expression as per your need
    return Regex.Replace(str, "[^a-zA-Z0-9_.]", "", RegexOptions.Compiled);
}

Setp 3 : Save file

 XmlDocument doc = new XmlDocument();
 doc.LoadXml(xmlstring);
 doc.PreserveWhitespace = true;
 doc.Save("data.xml");


来源:https://stackoverflow.com/questions/6591940/how-to-remove-special-characters-from-a-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!