2017-01-26 131 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