简体   繁体   中英

Parse XML string to List/DataTable in C#

I have a XML string given below with 2 columns no and Active

XML -

<RECORDS RECORDCOUNT="2">
    <RECORD COL_HEADER="0">
        <no>201738</no>
        <Active>-1</Active>
    </RECORD>
    <RECORD COL_HEADER="0">
        <no>201739</no>
        <Active>0</Active>
    </RECORD>
</RECORDS>

And to convert the above XML string to list i have tried to Parse with the below LINQ expression

LINQ - Expression

var result = XElement.Parse(xmlString)
                    .Descendants().Where(r => !string.IsNullOrEmpty(r.Value))
                    .Select(r => int.Parse(r.Value))
                    .ToList();

Error -

Input string was not in a correct format.

In the result set i am expecting both the columns with their respective values. Do i have to use datatable or any other other than list .

Please help! TIA

actually <RECORD COL_HEADER="0"> contain value, you must add to your Where an additional check to be like this

Where(r => !string.IsNullOrEmpty(r.Value) && (r.Name == "no" || r.Name == "Active"))

to obtain your expectation u can try this:

var result = XElement.Parse(xmlString)
.Descendants().
Where(x => x.Name == "RECORD")
.Select(x => new
{
    no = int.Parse(x.Element("no").Value),
    Active = int.Parse(x.Element("Active").Value)
}
).ToList();

You're only going down one level then attempting to parse the all the sub elements

<RECORD COL_HEADER="0">
  <no> 201738 </no>
  <Active> -1 </Active>
</RECORD>

into an int. You need to get them out individually, something like so

List<Record> records = XElement.Parse(xmlString)
    .Descendants("RECORD")
    .Select(x => new Record((int)x.Element("no"), (int)x.Element("Active")))
    .ToList();


public class Record
{
    public readonly int No;
    public readonly int Active;

    public Record(int no, int active)
    {
        this.No = no;
        this.Active = active;
    }
}

I prefer to use this way instead of using Descendants :

var result = XDocument.Parse(xmlString).Root?               // => RECORDS 
    .Elements()                                             // => RECORD
    .Select(c => new {
        no =  int.Parse(c.Element("no")?.Value ?? "0"), 
        active = c.Element("Active")?.Value == "-1"})
    .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