从XML加载到Observable集合

时间:2013-11-14 03:55:49

标签: c# xml observablecollection

将xml文件加载到Observable Collection时遇到问题。

我的XML看起来像

<?xml version="1.0" encoding="utf-8"?>
<Stock>
  <Assortment>
    <Item>Адельфан -  эзидрекс  таб  №10</Item>
    <Quantity>89</Quantity>
    <Price>3.0000</Price>
    <Summ>267</Summ>
    <Price1>3.0000</Price1>
    <Summ1>267</Summ1>
    <ValidDate>01.01.2031</ValidDate>
    <Manufacturer>КРКА</Manufacturer>
  </Assortment>
  <Assortment>
    <Item>Адельфан -  эзидрекс  таб  №10</Item>
    <Quantity>8</Quantity>
    <Price>3.0000</Price>
    <Summ>24</Summ>
    <Price1>3.0000</Price1>
    <Summ1>24</Summ1>
    <ValidDate>01.01.2019</ValidDate>
    <Manufacturer>КРКА</Manufacturer>
  </Assortment>
</Stock>

我尝试的代码就是这个。

            XDocument xml = XDocument.Load(filename);
                foreach (XElement xe in xml.Elements("Assortment"))
                {
                    _dummyCollection1.Add(new DummyClass1()
                    {
                        Наименование = xe.Element("Item").Value,
                        Количество = xe.Element("Quantity").Value,
                        Цена = xe.Element("Price").Value,
                        Сумма = xe.Element("Summ").Value,
                        Цена1 = xe.Element("Price1").Value,
                        Сумма1 = xe.Element("Summ1").Value,
                        Срокгодности = xe.Element("ValidDate").Value,
                        Производитель = xe.Element("Manufacturer").Value
                    });
                }
                BuyDataGrid.ItemsSource = _dummyCollection1;

我得到空的DataGrid。如何将xml传递给Observable Collection?

2 个答案:

答案 0 :(得分:1)

我找到了怎么做,万一有人需要;

                    XmlDocument doc = new XmlDocument();
                    doc.Load(filename);
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList nodes = root.SelectNodes("Assortment"); 
                    foreach (XmlNode node in nodes)
                    {
                        _dummyCollection1.Add(new DummyClass1()
                        {
                            Наименование = node["Item"].InnerText,
                            Количество = node["Quantity"].InnerText,
                            Цена = node["Price"].InnerText,
                            Сумма = node["Summ"].InnerText,
                            Цена1 = node["Price1"].InnerText,
                            Сумма1 = node["Summ1"].InnerText,
                            Срокгодности = node["ValidDate"].InnerText,
                            Производитель = node["Manufacturer"].InnerText
                        });
                    }
                    BuyDataGrid.ItemsSource = _dummyCollection1;

答案 1 :(得分:0)

您计划用作ObservableCollection集合的对象的类必须实现INotifyPropertyChanged

这是我的答案,举例说明如何填充dataGrid的模型

example