如何从txt文件中提取xml文件?

时间:2017-12-29 08:17:19

标签: xml text

我有一个以下格式的txt文件

<Information>
   <ID>1</ID>
   <Name>Sam</Name>
   <State>Seattle</State>
   <Country>US</Country>
</Information>

<Information>
   <ID>2</ID>
   <Name>srikhar</Name>
   <State>Las Vegas</State>
   <Country>US</Country>
</Information>

<Information>
   <ID>3</ID>
   <Name>sima</Name>
   <State>Ilinois</State>
   <Country>US</Country>
</Information>

我想将<Information> ...</Information>中的数据分隔到不同的XML文件中。基于以上场景,我需要获得3个XML文件。

有什么方法可以实现这个目标吗?

由于

2 个答案:

答案 0 :(得分:-1)

上次尝试过,但我学到了太危险的方法。你得到的输出非常“不精确”当我看到内容时,似乎是一个有效的xml结构,所以我的建议是使用 tinyxml 来提取。您可能需要重命名该文件以将扩展名更改为.xml。

答案 1 :(得分:-1)

你的xml格式不正确,所以你必须使用XmlReader,其设置等于Fragment。见下面的代码

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;

            XmlReader reader = XmlReader.Create(FILENAME, settings);

            while (!reader.EOF)
            {
                if (reader.Name != "Information")
                {
                    reader.ReadToFollowing("Information");
                }
                if (!reader.EOF)
                {
                    XElement information = (XElement)XElement.ReadFrom(reader);
                    string id = (string)information.Element("ID");
                    string filename = string.Format(@"c:\temp\informaton{0}.xml", id);
                    information.Save(filename);
                }
            }
        }
    }
}