2017-01-26 134 views
1

我有一個帶有XML數據塊的文檔,但每個塊之間都有純文本。我如何提取XML數據?將文本文件拆分爲XML

blah blah blah 
===: text text text :=== 
<?xml version="1.0" ?> 
    <Data> 
     <Line>information</Line> 
     <Line2>more information</Line2> 
    </Data> 
===: text text text :=== 
blah blah blah 
blah blah blah 
===: text text text :=== 
    <?xml version="1.0" ?> 
    <Data> 
     <Line>2nd information</Line> 
     <Line2>more information</Line2> 
    </Data> 
===: text text text :=== 
blah blah blah 

文本withing的===:===將永遠是不同的,但不需要被包括在內。

+1

更加具體談談那些'===:文字文字文字:==='線,它們是文字,總是存在於完全相同的辦法? –

+0

它每次都會有所不同,分隔符有一個時間戳和一堆其他信息 – frebbie

+0

信息還有點短。一個文件能否以XML開頭或者在第一個xml之前總會有一個'===:...:==='行? –

回答

1

這裏的這個將通過匹配(line.StartsWith("===:") && line.EndsWith(":==="))的任何行來劃分您的文件。

var fs = File.OpenText("file.xml"); 
var partitions = new List<string>(); 
var sb = new StringBuilder(); 
string line; 
while ((line = fs.ReadLine()) != null) 
{ 
    if (line.StartsWith("===:") && line.EndsWith(":===")) 
    { 
     if(sb.Length > 0) 
      partitions.Add(sb.ToString()); 
     continue; 
    } 

    sb.AppendLine(line); 
} 
if(sb.Length > 0) 
    partitions.Add(sb.ToString()); 

這其中建立一個分區,直到遇到一個分割線,然後開始另一個分區。

+0

它每次都會有所不同,分隔符有一個時間戳和一堆其他信息 – frebbie

+1

將此問題添加到問題中。這樣你就浪費時間和善意。 –

+0

@HenkHolterman現在已經完成了。這裏沒有經驗豐富的問題​​提供者soz – frebbie

-1

如果你想保持壓痕試試這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 



namespace ConsoleApplication43 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      string xml = ""; 
      string inputline = ""; 
      StreamReader reader = new StreamReader(FILENAME); 
      while ((inputline = reader.ReadLine()) != null) 
      { 
       if (inputline.Trim().StartsWith("<")) 
       { 
        xml += inputline + "\n"; 
       } 
      } 

     } 
    } 

} 
+0

不是每個xml行都以一個標籤開頭。 –

+0

然後發佈實際代表您的輸入的測試數據。 – jdweng