将文本文件拆分为XML

时间:2017-01-26 10:05:35

标签: c# 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

带有=== :: =的文本总是不同但不需要包括在内。

2 个答案:

答案 0 :(得分: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());

这个构建分区直到遇到分割线,然后它启动另一个分区。

答案 1 :(得分:-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";
                }
            }

        }
    }

}
相关问题