繁体   English   中英

如何使用C#的REGEX删除字符之间的空格,制表符和新行?

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

我如何使用存储在文本文件中的以下字符串删除">" and "<"">" and "</"之间的空格,制表符,换行符以及类似<wiretype />的空格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>

我尝试了以下操作,但并未删除所有空格:

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();
    }
}

为什么不使用:

XDocument xdoc = XDocument.Load(filename);
xdoc.Save(filename, SaveOptions.DisableFormatting);

它将删除xml文档中的所有格式。 有关更多详细信息,请参见SaveOptions.DisableFormatting

我想您最好的选择是获取</>之间的所有信息。

<[^>]*/>

然后,您可以用替换所有语言来对xml的匹配部分进行替换。

( |\n|\t) to be replaced by ""

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM