XML TO linq将元素列表导入ArrayList

时间:2012-06-10 11:10:52

标签: c# xml linq

我有这个XML文件设置,我怎么能(USING LINQ)将(StartItem)列表返回给ArrayList

并将(PriceItem)返回到另一个ArrayList

<Settings>
    <ConSetting SettingID="1">
         <Company CompanyID="1" CompanyName="CA" Code="*100#" Pin="11111" MobileName="M1">
            <StartItems StartID="1"> 094</StartItems>
            <StartItems StartID="2"> 095</StartItems>
            <StartItems StartID="4"> 097</StartItems>
            <StartItems StartID="5"> 098</StartItems>
        </Company>
        <Company CompanyID="2" CompanyName="CB" Code="*200#" Pin="22222" MobileName="M2">
            <StartItems StartID="1"> 099</StartItems>
            <StartItems StartID="2"> 093</StartItems>
            <StartItems StartID="3"> 091</StartItems>
            <StartItems StartID="4"> 092</StartItems>

        </Company>
    </ConSetting>
    <Price SettingID ="2" CompanyName="CA" >
             <Company CompanyID="1">
            <PriceItem P="40"> 50</PriceItem>
            <PriceItem P="90"> 100</PriceItem>
            <PriceItem P="200"> 225</PriceItem>

        </Company>
        <Company CompanyID="2" CompanyName="CB" >
            <PriceItem P="40"> 60</PriceItem>
            <PriceItem P="90"> 110</PriceItem>
            <PriceItem P="200"> 235</PriceItem>

        </Company>
    </Price>

</Settings>

2 个答案:

答案 0 :(得分:2)

XDocument在您的情况下很容易使用:

var doc = XDocument.Load("settings.xml");
var result = from items in doc.Descendants("StartItems")
             where items.Parent.Attribute("CompanyID").Value == "1"
             select new StartItem() 
             {
                 StartID = items.Attribute("StartID").Value,
                 Value = items.Value
             };
var Company1List = new ArrayList();

foreach(var item in result)
{
    Company1List.Add(item);
}

public class StartItem
{
    public string StartID { get; set; }
    public string Value { get; set; }
}

答案 1 :(得分:0)

您可能希望查看.NET中的XmlReader类

它应该能够轻松地解析此XML,然后您可以从节点中选择您想要的任何列表中的某些项目。

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx

看看这个问题并回答

Reading Xml with XmlReader in C#