开发者

How can I remove the spaces, tabs, new lines between characters using c#'s REGEX?

How can I remove the spaces, tab charac开发者_如何学编程ters, 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 ""
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜