簡體   English   中英

將 XML 字符串解析為 C# 中的 List/DataTable

[英]Parse XML string to List/DataTable in C#

我有一個XML string ,下面給出了 2 列noActive

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>

並將上面的XML string轉換為list ,我試圖用下面的LINQ expression Parse

LINQ - 表達式

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

錯誤 -

輸入字符串的格式不正確。

在結果集中,我期望兩列都有各自的值。 我是否必須使用datatable或除list以外的任何其他內容。

請幫忙! TIA

實際上 <RECORD COL_HEADER="0"> 包含值,你必須添加到你的 Where 一個額外的檢查是這樣的

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

為了獲得您的期望,您可以嘗試以下操作:

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

您只會下降一層然后嘗試解析所有子元素

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

成一個整數。 你需要把它們單獨拿出來,像這樣

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;
    }
}

我更喜歡使用這種方式而不是使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM