[英]How can i extract an xml files from a txt file?
我有以下格式的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文件。
有什么办法可以做到这一点?
谢谢
上次尝试过该方法,但我发现这样做太危险了。 您得到的输出非常“不精确”,正如我所看到的,它似乎是有效的xml结构,因此我的建议是使用tinyxml进行提取。 您可能需要重命名文件才能将扩展名更改为.xml。
您的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);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.