How can I remove the spaces, tab characters, new line characters between ">" and "<"
, ">" and "</"
and also the space between like <wiretype />
from the below string stored in a text file using C#?
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetReport xmlns="http://tempuri.org/">
<RequestContext xmlns="">
<userid>reds</userid><fcnumber>1</fcnumber><accountaccess /><wiretype /><currency /><accountheader>All</accountheader><clientname>Begum Noor</clientname><requestid>9999</requestid><ntid>reds</ntid>
</RequestContext>
<ReportParams>xyz</ReportParams>
</GetReport>
</soap:Body>
</soap:Envelope>
I tried the following but it didn't remove the all the spaces:
static void Main(string[] args)
{
string filename = args[0];
StringBuilder result = new StringBuilder();
if (System.IO.File.Exists(filename))
{
using (StreamReader streamReader = new StreamReader(filename))
{
String line;
Regex r = new Regex(@">\s+<");
while ((line = streamReader.ReadLine()) != null)
{
string newLine = r.Replace(line, @"><");
result.Append(newLine);
}
}
}
Console.WriteLine(result);
Console.ReadLine();
using (FileStream fileStream = new FileStream(filename, FileMode.OpenOrCreate))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write(result);
streamWriter.Close();
fileStream.Close();
}
}
Why don't you use:
XDocument xdoc = XDocument.Load(filename);
xdoc.Save(filename, SaveOptions.DisableFormatting);
it will remove all the formatting in your xml
document. See SaveOptions.DisableFormatting
for more details.
I guess you best shot is to get all the information between the <
and />
.
<[^>]*/>
Then you can do the replace on that matched part of the xml with the replace all of your language.
( |\n|\t) to be replaced by ""
来源:https://stackoverflow.com/questions/5275011/how-can-i-remove-the-spaces-tabs-new-lines-between-characters-using-cs-regex