且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 XML 中删除特殊字符

更新时间:2023-11-06 20:53:04

第一步:加载 Xml 文件到字符串

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:使用函数去除所有特殊字符

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 : 保存文件

Setp 3 : Save file

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