-4

我有一些 XML 文件,其中包含我想从文件中删除的带有字符串字符(垃圾)的行。我正在搜索可以做到这一点的代码,有人可以帮我吗?

<value key="EE_BELL_TIME">
  <val name="Siren Time" show="1" type="BYTE" size="8" poff="260" psize="8" pbitoff="0" />
  <posvalues>
    <pval name="1 minute" num="1" />
    zeqmmzv
    <pval name="3 minutes" num="3" />
    <pval name="4 minutes" num="4" />
    <pval name="8 minutes" num="8" />
    fmengu
    <pval name="10 minutes" num="10" />
    <pval name="15 minutes" num="15" />
    p
    <pval name="20 minutes" num="20" />
  </posvalues>
</value>
4

2 回答 2

1

C#中,您可以使用正则表达式作为查找 XML 标记的解决方案,如下所示:

class Program
{
    static void Main(string[] args)
    {
        // Open and read into a string the file containing the XML
        string s = System.IO.File.ReadAllText("file.xml");

        // You have too match (?>\<).*(?>\>), which also removes the line feeds
        var matches = Regex.Matches(s, @"(?>\<).*(?>\>)");

        // Use a StringBuilder to append the matches
        var sBuilder = new StringBuilder();

        // Loop through the matches
        foreach (Match item in matches)
        {
            sBuilder.Append(item.Value);
        }

        // Show the result
        Console.WriteLine(sBuilder.ToString());
    }
}
于 2013-01-31T12:31:48.057 回答
0

你可以用一种非常简单的方式做到这一点:

 string[] lines = File.ReadAllLines(xmlPath);
 File.WriteAllLines(xmlPath, lines.Where(l => l.StartsWith("<") && l.EndsWith(">")));

这只是一个非常简单的解决方案,但它应该适用于您的 xml 文件

更新代码

Encoding encoding = Encoding.GetEncoding(1252);
        string[] lines = File.ReadAllLines(xmlFile, encoding);
        List<string> result = lines.Select(line => line.TrimStart().TrimEnd()).Where(trim => trim.StartsWith("<") && trim.EndsWith(">")).ToList();
        File.WriteAllLines("XmlFile2.xml", result, encoding);

更新为不修剪线条:

Encoding encoding = Encoding.GetEncoding(1252);
        string[] lines = File.ReadAllLines(xmlFile, encoding);
        List<string> result = (from line in lines let trim = line.TrimStart().TrimEnd() where trim.StartsWith("<") && trim.EndsWith(">") select line).ToList();
        File.WriteAllLines("XmlFile2.xml", result, encoding);
于 2013-01-31T12:03:54.653 回答