简体   繁体   English

尝试使用Linq和C#解析XML并创建List信息

[英]Trying to parse XML and create a List information using Linq and C#

Very new to C# and Linq, lots to learn... I would like to be able to parse XML with Linq, and move a portion of the XML data into a List. 对于C#和Linq来说是非常新的东西,有很多东西要学习...我希望能够用Linq解析XML,并将XML数据的一部分移到List中。 The XML data is small, Initially (query 1 below) I was able to capture all nodes except the ACCT nodes. XML数据很小,最初(下面的查询1)我能够捕获除ACCT节点之外的所有节点。 My 2nd attempt was to create a 2nd query (ACCT query below) but it only successfully captures the 1st occurrence of ACCT . 我的第二次尝试是创建第二次查询(下面的ACCT查询),但是它仅成功捕获了第一次出现的ACCT。 searched for some time, found several examples but I have not been successful in implementing way to capture all occurrences of ACCT with Linq and c#. 搜索了一段时间,发现了几个示例,但是我没有成功实现使用Linq和c#捕获所有出现的ACCT的方式。 Seems like a VERY useful tool, any assistance would be appreciated. 好像是一个非常有用的工具,将不胜感激。

here is XML 这是XML

<?xml version="1.0" encoding="utf-8"?>
<ORDER>
  <EMPNUMBER>LDC</EMPNUMBER>
  <ITEMNAME>NEWNAME_GR0045LDS01.JPG</ITEMNAME>
  <DATETIMESTAMP>04-19-2015</DATETIMESTAMP>
  <DEPT>HMES</DEPT>
<SHIPMENTLIST>
  <ACCT>2222222222</ACCT>
  <ACCT>1111111111</ACCT>
</SHIPMENTLIST>
</ORDER>

here is current class 这是当前班级

public class clsShipACCT
{

    public string strShipACCT
    {
        get;
        set;
    }
}

here is logic(commented out items show failed attempts list) 这是逻辑(注释掉的项目显示失败尝试列表)

//this gets all xml details except account(ACCT)
           var query1 = from item in xDoc.Descendants("ORDER")   // xDoc.Elements() //xDoc.Descendants("ORDER") // xDoc.Root.Elements("ORDER")
                        select new
                        {
                            EmpNum = item.Element("EMPNUMBER").Value,
                            ItemName = item.Element("ITEMNAME").Value,
                            OrderDate = Convert.ToDateTime(item.Element("DATETIMESTAMP").Value),

                        };


//attempt to get ACCT detail
            var Acctlist = from P in xDoc.Root.Descendants("SHIPMENTLIST")
                         select new { b = P.Element("ACCT").Value };


            foreach(var p in ACCTlist)
                ACCTgram.WriteLog("Parsed XML Acct: " + p);


//failed attempt to capture ACCT in list: 
//           List<clShipACCT> testList = ACCTlist.ToList<clShipACCT>(); 

            //////var ACCTlist = (from P in xDoc.Descendants("SHIPMENTLIST")
            //////               select new clShipACCT { strShipACCT = childitem.Element("ACCT").Value }).ToList();
            //////testShipACCTList.AddRange(ACCTlist);

Use .Elements method - this method return all elements with given name 使用.Elements方法-此方法返回具有给定名称的所有元素
.Element method will return only first element .Element方法将仅返回第一个元素

var shipments = xDoc.Root.Descendants("SHIPMENTLIST")

List<String> acctList = new List<String>();
foreach(var accts in shipments)
{
    acctList.AddRange(accts.Elements("ACCT").Select(acct => acct.Value));
}

foreach(string acct in acctlist)
    ACCTgram.WriteLog("Parsed XML Acct: " + acct);
var result = xDoc.Root.Element("SHIPMENTLIST").Elements("ACCT").Select(x => x.Value).ToList();

Using the xml in the post, this should yield a 在帖子中使用xml,这应该会产生一个

List<string> 

of the values in the ACCT fields. ACCT字段中的值。

You are very close, just add your accounts search to your first query and generic object creation. 您非常接近,只需将帐户搜索添加到第一个查询和通用对象创建中即可。

Change this to be: 更改为:

var query1 = from item in xDoc.Descendants("ORDER")   // xDoc.Elements() //xDoc.Descendants("ORDER") // xDoc.Root.Elements("ORDER")
select new
{
    EmpNum = item.Element("EMPNUMBER").Value,
    ItemName = item.Element("ITEMNAME").Value,
    OrderDate = Convert.ToDateTime(item.Element("DATETIMESTAMP").Value),
    Accts = item.Element("SHIPMENTLIST").Elements("ACCT").Select(x => x.Value).ToList()
};

//this works in LinqPad...Elements() return multiple instances... //这适用于LinqPad ... Elements()返回多个实例...

void Main()
{
    XDocument doc= XDocument.Load(@"d:\test2.xml");
    var orders = doc.Root.Elements("ORDER")
        .Select (o => new Order
            {
                EmpNumber=o.Element("EMPNUMBER").Value,
                ItemName=o.Element("ITEMNAME").Value,
                TimeStamp=o.Element("DATETIMESTAMP").Value,
                Shipments=o.Element("SHIPMENTLIST").Elements("ACCT").Select (e => new Shipment{Account= e.Value}).ToList()
            }
        );

    orders.Dump();  
}



class Order
{
    public Order ()
    {
        this.Shipments=new List<Shipment>();
    }
    public string EmpNumber { get; set; }
    public string ItemName { get; set; }
    public string TimeStamp { get; set; }  //should be date time
    public string Department { get; set; }
    public List<Shipment> Shipments { get; set; }
}


class Shipment
{
    public string Account { get; set; }
}

I assumed the following xml: added ORDERS as the root element since one order in xml is really trivial... 我假设使用以下xml:将ORDERS添加为根元素,因为xml中的一个订单确实很简单。

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

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