简体   繁体   English

C#从文本文件读取XmlElement

[英]C# Read XmlElement from a Text file

I have a text file contains 500+ xmlelements like the following: 我有一个包含500多个xmlelements的文本文件,如下所示:

<Data a="a" b="b" c="c" d="d"><Date runDt="01-01-1900" /></Data>

Can someone please show me how to read/load it so I can retrieve certain attributes/elements? 有人可以告诉我如何读取/加载它,以便我可以检索某些属性/元素吗? And once I manipulate the data, write it back to a new text file (and needs to be a .txt file without any xml headers). 然后,一旦我处理了数据,就将其写回到新的文本文件中(并且需要是一个没有任何XML标头的.txt文件)。

Thanks :) 谢谢 :)

Easiest way is to use: 最简单的方法是使用:

using System.Xml; 使用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);

Will print 将打印

a 一种

Using XmlDocument is very easy, just check its fields, variables and methods. 使用XmlDocument非常简单,只需检查其字段,变量和方法即可。

Try this 尝试这个

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();

        }
    }
}
​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM