C#从Text文件中读取XmlElement

时间:2015-12-17 17:32:30

标签: c# xml

我有一个包含500多个xmlelements的文本文件,如下所示:

Select a.nome, s.descricao, t.data
FROM Aluno a
join Serie s on (s.id_aluno = a.id_aluno)
join Treino t on (t.id_serie = s.id_serie)

有人可以告诉我如何阅读/加载它以便我可以检索某些属性/元素吗?一旦我操作数据,将其写回一个新的文本文件(并且需要是一个没有任何xml标题的.txt文件)。

谢谢:)

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用:

  

使用System.Xml;

XmlDocument xml = new XmlDocument ();
xml.InnerXml = @"<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>";
Console.WriteLine (xml.ChildNodes [0].Attributes [0].InnerText);

将打印

  

使用XmlDocument非常简单,只需检查其字段,变量和方法即可。

答案 1 :(得分:0)

试试这个

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>\n" +
                "<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>\n" +
                "<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>\n" +
                "<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>\n" +
                "<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>\n";

            //xml can only contain one root tag.  Need to wrap xml in root tag if one is missing
            input = string.Format("<Root>{0}</Root>", input);

            XDocument doc = XDocument.Parse(input);

            // if loading from file
            //string input = File.ReadAllText(filename);
            //input = string.Format("<Root>{0}</Root>", input);
            //XDocument doc = XDocument.Load(filename);

            var results = doc.Descendants("Data").Select(x => new
            {
                a = x.Attribute("a").Value,
                b = x.Attribute("b").Value,
                c = x.Attribute("c").Value,
                d = x.Attribute("d").Value,
                date = DateTime.Parse(x.Element("Date").Attribute("runDt").Value)
            }).ToList();

        }
    }
}
​
相关问题