简体   繁体   中英

C# Read XmlElement from a Text file

I have a text file contains 500+ xmlelements like the following:

<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).

Thanks :)

Easiest way is to use:

using 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.

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

        }
    }
}
​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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