XML文档布局并将其连接到我的VB表单 [英] XML Document layout and connecting it to my VB form

查看:49
本文介绍了XML文档布局并将其连接到我的VB表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,伙计们!

在尝试在购物车中调用数据之前,我一直试图弄清楚如何创建XML文件来存储数据.在尝试将其实现到我的原始作品之前,我已经为此启动了一个全新的项目.我不确定我是否 正在将信息正确地实现到XML文件中:

I've been trying to figure out how to create an XML file to store data in before calling upon that data in a shopping cart. I've started an entirely new project for this before attempting to implement it into my original piece. I'm not entirely sure if I am implementing the information correctly into the XML file:

<?xml version="1.0" encoding="utf-8" ?>
<cart>
  
  <items category="beverages">
    <drink>Still Water</drink>
    <Amount>1</Amount>
    <price>£1</price>
  </items>

  <items category="beverages">
    <drink>Sparkling Water</drink>
    <amount>1</amount>
    <price>£1.20</price>
  </items>

  <items category="beverages">
    <drink>Coca Cola</drink>
    <amount>1</amount>
    <price>£1.25</price>
  </items>

  <items category="beverages">
    <drink>Pepsi</drink>
    <amount>1</amount>
    <price>£1.25</price>
  </items>

  <items category="beverages">
    <drink>Mountain Dew</drink>
    <amount>1</amount>
    <price>£1</price>
  </items>

  <items category="beverages">
    <drink>Lucosade Original</drink>
    <amount>1</amount>
    <price>£1</price>
  </items>

  <items category="beverages">
    <drink>Lemonade</drink>
    <amount>1</amount>
    <price>£0.85</price>
  </items>

  <items category="alcoholicBeverages">
    <drink>Fosters</drink>
    <amount>6</amount>
    <price>£4</price>
  </items>

</cart>

此外,我想知道如何将其连接到表单,以便将这些项目添加到所需的列表框中.我一直在环顾四周,并且从其他人那里找到了一些代码,但是我不完全理解,所以我宁愿不实现我不喜欢的代码 理解.另外,我不确定如何使代码适应我自己的形式.

Further, I would like to know how to connect this to my form so I can add these items into the desired listbox. I have been looking around and I have found some code from others but I don't understand it entirely so I would rather not implement code I don't understand. Also, I am not entirely sure on how to adapt the code to my own forms.

推荐答案

Cobi,

我修改了我先前在其他主题中发布给您的内容.与我今天上午发布的类相比,该类的类型略有不同,因为它是一个单独的集合(因此您不需要自己的List(Of ClassName)):

I have modified what I posted to you earlier in your other thread. This is a slightly different type of class than what I posted this morning in that it's a collection on its own (so you don't need your own List(Of ClassName)):

Option Strict On Option Explicit On Option Infer Off Imports System.IO Imports System.IO.Path Public Class ProductsCollection Inherits System.Collections.CollectionBase Public Enum CategoryType NA FrozenProducts Beverages Groceries End Enum Public Class CollectionItems Private _category As CategoryType Private _itemName As String Private _retailPrice As Decimal Friend Sub New(ByVal category As CategoryType, _ ByVal itemName As String, _ ByVal retailPrice As Decimal) Try If category = CategoryType.NA Then Throw New ArgumentException("The category must be set.") ElseIf String.IsNullOrWhiteSpace(itemName) Then Throw New ArgumentException("The item name cannot be null or empty.") ElseIf retailPrice <= 0 Then Throw New ArgumentOutOfRangeException("Retail Price", "Must be a positive value." & vbCrLf) Else _category = category _itemName = itemName.Trim _retailPrice = retailPrice End If Catch ex As Exception Throw End Try End Sub Public ReadOnly Property Category As CategoryType Get Return _category End Get End Property Public ReadOnly Property Category_String As String Get Select Case _category Case CategoryType.FrozenProducts Return "Frozen Products" Case Else Return _category.ToString End Select End Get End Property Public ReadOnly Property ItemName As String Get Return _itemName End Get End Property Public ReadOnly Property RetailPrice As Decimal Get Return _retailPrice End Get End Property Public ReadOnly Property RetailPrice_String As String Get Return _retailPrice.ToString("c2") End Get End Property Public Overrides Function ToString() As String Return String.Format("{0} | {1} | {2:c2}", _ _itemName, _ _category, _ _retailPrice) End Function End Class Public Sub Add(ByVal category As CategoryType, _ ByVal itemName As String, _ ByVal retailPrice As Decimal) Try If List.Count > 0 Then Dim ci As CollectionItems = Item(category, itemName, False) If ci IsNot Nothing Then Throw New ArgumentException("The item is already in the collection.") Else List.Add(New CollectionItems(category, itemName, retailPrice)) End If Else List.Add(New CollectionItems(category, itemName, retailPrice)) End If Catch ex As Exception Throw End Try End Sub Public Sub Remove(ByVal index As Integer) Try If index > Count - 1 OrElse index < 0 Then Throw New ArgumentOutOfRangeException("Index", "The collection does not contain this index." & vbCrLf) Else List.RemoveAt(index) End If Catch ex As Exception Throw End Try End Sub Public Sub Remove(ByVal category As CategoryType, _ ByVal itemName As String) Try Dim ci As CollectionItems = Item(category, itemName) If ci IsNot Nothing Then List.Remove(ci) End If Catch ex As Exception Throw End Try End Sub Public Sub ExportToXML(ByVal filePath As String) Try If String.IsNullOrWhiteSpace(filePath) Then Throw New ArgumentException("The file path cannot be null or empty.") Else Dim fi As New FileInfo(filePath) If fi.Exists Then fi.Delete() End If If Not Utilities.FileDirectoryCanBeWrittenTo(fi.Directory.FullName) Then Throw New UnauthorizedAccessException("You do not have permission to write to this directory.") Else If List.Count > 0 Then Dim xDoc As XElement = _ <Products> <%= From ci As CollectionItems In GetEnumerable() Select _ <Product> <%= New XAttribute("Category", ci.Category.ToString) %> <%= New XAttribute("ItemName", ci.ItemName) %> <%= New XAttribute("RetailPrice", ci.RetailPrice.ToString) %> </Product> %> </Products> xDoc.Save(fi.FullName) End If End If End If Catch ex As Exception Throw End Try End Sub Public Sub ImportFromXML(ByVal filePath As String) Try List.Clear() If String.IsNullOrWhiteSpace(filePath) Then Throw New ArgumentException("The file path cannot be null or empty.") Else Dim fi As New FileInfo(filePath) If Not fi.Exists Then Throw New FileNotFoundException("The file path could not be located.") Else Dim xDoc As XElement = XElement.Load(fi.FullName) For Each productInfo As XElement In xDoc...<Product> List.Add(New CollectionItems(DirectCast([Enum].Parse(GetType(CategoryType), productInfo.@Category), CategoryType), _ productInfo.@ItemName, CDec(productInfo.@RetailPrice))) Next End If End If Catch ex As Exception Throw End Try End Sub Public Function GetEnumerable() As IEnumerable(Of CollectionItems) Dim retVal As IEnumerable(Of CollectionItems) = Nothing Try If List.Count > 0 Then Dim qry As System.Collections.Generic.IEnumerable(Of CollectionItems) = _ From ci As CollectionItems In List.Cast(Of CollectionItems)() If qry.Count > 0 Then retVal = qry End If End If Catch ex As Exception Throw End Try Return retVal End Function Public ReadOnly Property Item(ByVal index As Integer) As CollectionItems Get Try If index > Count - 1 OrElse index < 0 Then Throw New ArgumentOutOfRangeException("Index", "The collection does not contain this index." & vbCrLf) Else Return DirectCast(List(index), CollectionItems) End If Catch ex As Exception Throw End Try End Get End Property Public ReadOnly Property Item(ByVal category As CategoryType, _ ByVal itemName As String, _ Optional ByVal throwIfNotFound As Boolean = True) As CollectionItems Get Try If String.IsNullOrWhiteSpace(itemName) Then Throw New ArgumentException("The item name cannot be null or empty.") Else If List.Count > 0 Then Dim qry As System.Collections.Generic.IEnumerable(Of CollectionItems) = _ From ci As CollectionItems In GetEnumerable() _ Where ci.Category = category AndAlso _ ci.ItemName.ToLower.Replace(" "c, "") = itemName.ToLower.Replace(" "c, "") If qry.Count <> 1 Then If throwIfNotFound Then Throw New ArgumentException("The item is not in the collection.") Else Return Nothing End If Else Return qry.First End If Else Return Nothing End If End If Catch ex As Exception Throw End Try End Get End Property End Class Public NotInheritable Class Utilities Private Sub New() End Sub Public Shared Function _ FileDirectoryCanBeWrittenTo(ByVal directoryToTest As String) As Boolean Dim retVal As Boolean = True Try If String.IsNullOrWhiteSpace(directoryToTest) Then Throw New ArgumentException("The directory name cannot be null or empty.") Else Dim di As New DirectoryInfo(directoryToTest) If Not di.Exists Then Throw New DirectoryNotFoundException("The directory could not be located.") Else Dim testPath As New FileInfo(Combine(di.FullName, "Test.tmp")) If testPath.Exists Then testPath.Delete() End If File.WriteAllText(testPath.FullName, String.Empty) testPath.Refresh() retVal = testPath.Exists If testPath.Exists Then testPath.Delete() End If End If End If Catch ex As Exception retVal = False End Try Return retVal End Function End Class


正如您在上面看到的那样,有一种方法可以导入到XML文件中,还有一种相应的方法可以从XML导入.

As you can see above, there's a method that I put in there to export to an XML file and a corresponding method to import from an XML.

在表单的代码中,我使用以下代码对其进行了测试:

In the form's code, I tested it using this:

Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Dim products As New ProductsCollection With products Dim prodCategory As ProductsCollection.CategoryType = _ ProductsCollection.CategoryType.Beverages .Add(prodCategory, "Still Water", 1) .Add(prodCategory, "Sparkling Water", 1.2D) .Add(prodCategory, "Coca-Cola", 1.25D) .Add(prodCategory, "Pepsi", 1.25D) .Add(prodCategory, "Mountain Dew", 1) .Add(prodCategory, "Lucosade Original", 1) .Add(prodCategory, "Lemonade", 0.85D) .Add(prodCategory, "Fosters", CDec((4 / 6))) End With Stop ' Hover your mouse over "products" and have ' a look around. Following that, continue: Dim desktop As String = _ Environment.GetFolderPath(Environment.SpecialFolder.Desktop) Dim xPath As String = _ IO.Path.Combine(desktop, "TestMe.xml") products.ExportToXML(xPath) Stop products.ImportFromXML(xPath) Stop End Sub End Class


代码每次停止都将停止(就像断点一样),然后您可以将鼠标悬停在范围内的任何变量上以查看其值.

The code will stop each time it gets to stop (just like a breakpoint will) and you can then hover your mouse over any variable which is then in scope to see the value of it.

上面的一个将在您的桌面上放置一个小的.xml文件(称为"TestMe.xml"),下面显示了内容:

The one above will put a small .xml file on your desktop (called "TestMe.xml") and the following shows the contents:

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product Category="Beverages" ItemName="Still Water" RetailPrice="1" />
  <Product Category="Beverages" ItemName="Sparkling Water" RetailPrice="1.2" />
  <Product Category="Beverages" ItemName="Coca-Cola" RetailPrice="1.25" />
  <Product Category="Beverages" ItemName="Pepsi" RetailPrice="1.25" />
  <Product Category="Beverages" ItemName="Mountain Dew" RetailPrice="1" />
  <Product Category="Beverages" ItemName="Lucosade Original" RetailPrice="1" />
  <Product Category="Beverages" ItemName="Lemonade" RetailPrice="0.85" />
  <Product Category="Beverages" ItemName="Fosters" RetailPrice="0.666666666666667" />
</Products>

只要有可能,我都会尝试使用属性而不是元素(有时甚至是元素)来保持文件较小.那就是你在上面看到的.

Whenever I can, I try to use attributes rather than elements (and sometimes both) just to keep the file size small. That's what you see above.

我希望能有所帮助. :)

I hope that helps. :)


这篇关于XML文档布局并将其连接到我的VB表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆