2013-01-31 122 views
-4

我有一些XML文件,其中包含需要從文件中刪除的字符串(垃圾)的行。 我正在尋找一個可以做到的代碼,有人可以幫助我嗎?從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> 
+0

說不上來,如果它是一個快速的解決方案,但也許做一個正則表達式定義的標記和什麼標記包含像屬性和東西,然後獲取匹配集合,並將其全部寫入一個新文件,我認爲這將是最簡單的方法 –

回答

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); 
+0

如果XML沒有換行符,該怎麼辦? –

+0

然後代碼剪切失敗。正如我所說:這是一個非常簡單的解決方案,但它應該適用於提供的xml。可能有更好的方法。 – Tomtom

+0

當我運行此代碼(Tomtom用戶)並將內容保存到一個新的XML文件時,它將它保存到一個空的XML文件,爲什麼? 我之前或之後忘了做錯了嗎? – Orionlk

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

如果XML具有嵌套元素,該怎麼辦? –

+0

你是什麼意思? –

+0

那種正則表達式在這種情況下會起作用嗎? –