2017-06-13 130 views
0

我試圖讀取/保存xml文件到datagrid,我使用數據集來做到這一點。現在,我已經成功將XML文件中的數據加載到數據網格,代碼如下:WPF將數據集保存到xml

public class StoreDbDataSet 
{ 
    internal static DataSet ReadDataSet() 
    { 
     DataSet ds = new DataSet(); 
     ds.ReadXmlSchema("store.xsd"); 
     ds.ReadXml("store.xml"); 
     return ds; 
    } 

} 

和:

public class StoreDb 
{ 
    public ObservableCollection<Product> GetProducts() 
    { 
     DataSet ds = StoreDbDataSet.ReadDataSet(); 

     ObservableCollection<Product> products = new ObservableCollection<Product>(); 
     foreach (DataRow productRow in ds.Tables["Products"].Rows) 
     { 
      products.Add(new Product((string)productRow["ModelNumber"], 
       (string)productRow["ModelName"], (string)productRow["InputAddress"], 
       (string)productRow["OutputAddress"], (string)productRow["DiagAddress"], 
       (string)productRow["Description"], (byte)productRow["CategoryID"], 
       (string)productRow["CategoryName"], (string)productRow["ProductImage"])); 
     } 
     return products; 
    } 
} 

XAML文件:

<DataGrid Name="dgBasicInfo" ItemsSource="{Binding ProductsView, Mode=TwoWay}" CanUserResizeColumns="False" AutoGenerateColumns="False" Margin="10,10,10,15" BorderThickness="5" FontSize="14" Background="White"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="SlaveId" Binding="{Binding CategoryID}" /> 
     <DataGridTextColumn Header="ModelName" Binding="{Binding ModelName}"/> 
     <DataGridTextColumn Header="CategoryName" Binding="{Binding CategoryName}" /> 
     <DataGridTextColumn Header="InputAddress" Binding="{Binding InputAddress}" /> 
     <DataGridTextColumn Header="OutputAddress" Binding="{Binding OutputAddress}" /> 
     <DataGridTextColumn Header="DiagAddress" Binding="{Binding DiagAddress}" /> 
     <DataGridTextColumn Header="Specification" Binding="{Binding Description}" /> 
    </DataGrid.Columns> 
</DataGrid> 

視圖模型:

public ICollectionView ProductsView 
    { 
     get { return _ProductsView; } 
     set 
     { 
      _ProductsView = value; 
      NotifyPropertyChanged(); 
     } 
    } 

我的問題是當我改變了數據網格數據,我怎樣才能保存更改爲XML?提前致謝!

--------------------------- update ------------------ -------------

private void RefreshProductList() 
    { 
     ProductsView = new ListCollectionView(sdb.GetProducts()) 
     { 
      Filter = obj => 
      { 
       var Product = (Product)obj; 
       return SelectedProduct != null && Product.ModelNumber == SelectedProduct.ModelNumber; 
      } 
     }; 
    } 

    private Product selectedProduct; 
    public Product SelectedProduct 
    { 

     get { return selectedProduct; } 
     set 
     { 
      if (selectedProduct != value) 
      { 
       selectedProduct = value; 
       NotifyPropertyChanged(); 
       RefreshProductList(); 
       RefreshModule(); 
       RefreshCommunication(); 
       List<Product> productlist = ProductsView.ToList(); 
       File.WriteAllText("store.xml", productlist.ToXML()); 
      } 
     } 
    } 
+0

如何[中WriteXML ](https://msdn.microsoft.com/en-us/library/system.data.datase t.writexml(V = vs.110)的.aspx)? – CodingYoshi

+0

我這樣做了,但它只是創建一個新的空XML文件。 –

+0

你寫給xml的哪個組件? 您將您的數據綁定到ProductsView, 請參閱setter方法的更改。如果發生更改,則將其寫入XML。 –

回答

0

問題是你正在閱讀XML作爲數據集,而不是把它讀作產品,並將其作爲產品的陣列除下文

你的XML格式應該是這樣的

<ArrayOfProduct> 
<Product> 
<ModelNumber>abc</ModelNumber> 
//remaking properties 
</Product> 
</ArrayOfProduct> 

創建一個擴展方法類,這幫助你轉換XML列出反之亦然

public static class ExtensionMethods 
{ 
    /// <summary> 
    /// Converts given class to XML using xml serialization 
    /// </summary> 
    /// <typeparam name="T">Type of Class</typeparam> 
    /// <param name="classObject">Class to be serialized</param> 
    /// <returns>Xml string</returns> 
    public static string ToXML<T>(this T classObject) where T : class 
    { 
     XmlSerializer xmls = new XmlSerializer(typeof(T)); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      XmlWriterSettings settings = new XmlWriterSettings(); 
      settings.Encoding = new UTF8Encoding(false); 
      settings.Indent = true; 
      settings.IndentChars = "\t"; 
      settings.NewLineChars = Environment.NewLine; 
      settings.OmitXmlDeclaration = true; 
      settings.ConformanceLevel = ConformanceLevel.Document; 
      using (XmlWriter writer = XmlTextWriter.Create(ms, settings)) 
      { 
       xmls.Serialize(writer, classObject); 
      } 

      string xml = Encoding.UTF8.GetString(ms.ToArray()); 
      return xml; 
     } 
    } 

    /// <summary> 
    /// Converts given XML string to class of type T 
    /// </summary> 
    /// <typeparam name="T">Type to be converted</typeparam> 
    /// <param name="XmlData">xml string</param> 
    /// <returns>class of Type T</returns> 
    public static T ToClass<T>(this string XmlData) 
    { 
     XmlSerializer serializer = new XmlSerializer(typeof(T)); 
     T newClass; 
     using (XmlTextReader reader = new XmlTextReader(new StringReader(XmlData))) 
     { 
      //reader.Namespaces = false; 
      newClass = (T)serializer.Deserialize(reader); 
     } 
     return newClass; 
    } 
} 

現在你的店分貝應該是這樣的

public class StoreDb 
{ 
    public ObservableCollection<Product> GetProducts() 
    { 
     string StoreData = string.Empty; 
     using(StreamReader sr = new StreamReader("store.xml")) 
      { 
       StoreData = sr.ReadToEnd(); 
      } 
     ObservableCollection<Product> products = new ObservableCollection<Product>(StoreData.ToClass<List<Product>()); 

     return products; 
    } 
} 

變化productsView到的ObservableCollection

private ObservableCollection<Product> _ProductsView; 
public ObservableCollection<Product> ProductsView 
    { 
     get { return _ProductsView; } 
     set 
     { 
      _ProductsView = value; 
      NotifyPropertyChanged(); 
     } 
    } 

現在,經過更改保存XML如下

File.WriteAllText("store.xml",ProductsView.ToList().ToXml()); 
+0

非常感謝您的回覆,但是當我嘗試通過代碼加載xml數據時出現錯誤。'InvalidOperationException:不是預期的。 ' 我的XML文件的樣子: '<?XML版本= 「1.0」 獨立= 「是」> .... ' –

+0

我給你的XML格式嘗試保存這樣 – Krishna

+0

XML我看不出區別這兩個XML文件之間 –