简体   繁体   中英

C# Conversion of CSV to XML using LINQ

The task is to convert the CSV file into XML.

var x = from line in File.ReadAllLines(@"d:\sample.txt")
        where !line.StartsWith("#") && line.Length>0
        let parts=line.Split(',')
       select new
       {
         XmlFile= new XElement("root",
                                new XElement("ISBN",parts[0]),
                                new XElement("Title",parts[1])
                               )

       };

Questions

1 ) How to dispose the stream (Using Statement with LINQ).

2) How to save the selection into "sample.xml" file?

3) How to bind an Xml file to GridView ?(Do i need to use XmlDataSource ?).

4) Using Linq is it possible to create XSD for my XML ? (without using XSD.exe).

1) File.ReadAllLines performs a File.Close, so you shouldn't have a stream problem.

2) You need to put your Linq query inside your XElement declaration, that way you get an XElement out of it, and not an IEnumerable of XElements (see below)

3 & 4 someone else can answer... ;)

(Warning, following code untested) :

var xmlFile = new XElement("root", 
        from line in File.ReadAllLines(@"d:\sample.txt")
        where !line.StartsWith("#") && line.Length>0
        let parts=line.Split(',')
        select new XElement("book",
                            new XElement("ISBN",parts[0]),
                            new XElement("Title",parts[1])
                           )
        );

1) I don't think you need to explicitly dispose of a stream. Did you detect a leak?
2) Instead of creating objects (of an anon-type) with an XMLFile property, collate a list of XML Elements

...
select new XElement("root",
                                new XElement("ISBN",parts[0]),
                                new XElement("Title",parts[1])
                               )

Now you can programatically create an XmlDocument or parent XElement, add the list as child elements and save it to a file using a member function on the above XML classes.

3) Data-binding: look for XmlDataProvider MSDN Docs .
4) an XSD is also XML. So no reason why you can't programatically generate it.. although I've never tried it. Unless you're looking at automatically generating the schema from the xml file that you created in Step2.. in which case I do not know the answer to that.. Not sure if any tool can generate the right format specification from a valid implementation of the spec.

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