简体   繁体   English

如何使用 vb.net 在 xml 中保存复选框值

[英]How to save checkbox value in xml using vb.net

I know, maybe this is a question that comes up quite often, but I haven't been able to work on it.我知道,也许这是一个经常出现的问题,但我一直无法解决这个问题。 How can I save this checkbox values in an XML file using VB.Net?如何使用 VB.Net 将此复选框值保存在 XML 文件中?

 Private Sub ChkVul_Click(sender As Object, e As EventArgs) Handles ChkVul.Click
    If ChkVul.Checked = True Then
        Me.pnlInsert.Visible = True
    Else
        Me.pnlInsert.Visible = False
    End If
End Sub

Before I provide you with an answer, I wanted to recommend a slight code change.在我为您提供答案之前,我想建议您对代码稍作更改。 Since you are setting the Boolean value of pnlInsert.Visible based on a condition, which itself returns a Boolean value, simply get rid of the conditional check in the first place:由于您根据条件设置 pnlInsert.Visible 的pnlInsert.Visible值,该条件本身返回 Boolean 值,因此只需首先摆脱条件检查:

pnlInsert.Visible = ChkVul.Checked

Now to your question.现在回答你的问题。 What you are essentially asking is how to write a value to an XML file.您实质上要问的是如何将值写入 XML 文件。 Something to consider is that XML is only a markup language.需要考虑的是 XML 只是一种标记语言。 At the end of the day, an XML file is simply a file that contains formatted text.归根结底,XML 文件只是一个包含格式化文本的文件。

If you do not already have an XML file to read from, simply create a new instance of a XDocument ( documentation ).如果您还没有要读取的 XML 文件,只需创建一个 XDocument 的新实例( 文档)。 If you do have an XML file, then create a new instance of a XDocument by calling the static XDocument.Load method ( documentation ).如果您确实有 XML 文件,则通过调用 static XDocument.Load 方法( 文档)创建 XDocument 的新实例。 Here is a function that takes in a file location and attempts to load a XDocument, if it is unable to then it returns a blank XDocument with a single <root> element:这是一个 function,它接受一个文件位置并尝试加载 XDocument,如果它无法加载,则它返回一个带有单个<root>元素的空白 XDocument:

Private Function LoadOrCreateXml(filename As String) As XDocument
    Dim document = New XDocument()
    document.Add(New XElement("root"))

    Try
        If (Not String.IsNullOrWhiteSpace(filename) AndAlso IO.File.Exists(filename)) Then
            document = XDocument.Load(filename)
        End If
    Catch ex As Exception
        ' for the sake of this example, just silently fail
    End Try

    Return document
End Function

Now that you have an XDocument, it is just a matter of writing the value.现在您有了 XDocument,只需编写值即可。 You did not provide any details as to where the value should go or what the tag name should be, so I am going to assume that it should be a child of the <root /> element and the value would look something like this: <ChkVul>true/false</ChkVul> .您没有提供关于值应该在哪里 go 或标签名称应该是什么的任何详细信息,所以我假设它应该是<root />元素的子元素,并且值看起来像这样: <ChkVul>true/false</ChkVul>

To do this, we will need to get the <root /> element by calling the Element method ( documentation ) on the XDocument to get the element and then call the Add method ( documentation ) on the resulting XElement to add our node with the value:为此,我们需要通过调用 XDocument 上的 Element 方法( 文档)来获取<root />元素以获取该元素,然后在生成的 XElement 上调用 Add 方法( 文档)以将我们的节点添加到该值:

Dim document = LoadOrCreateXml("my-xml-file.txt")
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))

The final piece of all this is to write the in-memory XDocument back to the file.所有这一切的最后一部分是将内存中的 XDocument 写回文件。 You can leverage the XDocument.Save method ( documentation ):您可以利用 XDocument.Save 方法( 文档):

Dim filename = "my-xml-file.txt"
Dim document = LoadOrCreateXml(filename)
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
document.Save(filename)

Maybe this is what you have in mind.也许这就是你的想法。 I tested this with other controls,我用其他控件对此进行了测试,

Public Class Form1

    Private SavePath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                                                  "MyControls.xml") 'some valid path <-----------<<<

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        SaveCheckedState(ChkVul, "ChkVul", True)
    End Sub

    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If IO.File.Exists(SavePath) Then
            Try
                MyControls = XElement.Load(SavePath)
                For Each el As XElement In MyControls.Elements
                    Dim ctrl() As Control = Me.Controls.Find(el.@name, True)
                    If ctrl.Length > 0 Then
                        Dim chkd As System.Reflection.PropertyInfo = ctrl(0).GetType().GetProperty("Checked")
                        Dim chkdV As Boolean = Boolean.Parse(el.@checked)
                        chkd.SetValue(ctrl(0), chkdV)
                    End If
                Next
            Catch ex As Exception
                'todo
            End Try
        End If
    End Sub

    Private Sub ChkVul_CheckedChanged(sender As Object, e As EventArgs) Handles ChkVul.CheckedChanged
        If ChkVul.Checked Then
            Me.pnlInsert.Visible = True
        Else
            Me.pnlInsert.Visible = False
        End If
        SaveCheckedState(ChkVul, "ChkVul")
    End Sub

    Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
        SaveCheckedState(RadioButton1, "RadioButton1")
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        SaveCheckedState(CheckBox1, "CheckBox1")
    End Sub

    Private MyControls As XElement = <controls>
                                     </controls>

    Private Sub SaveCheckedState(Ctrl As Control,
                                 Name As String,
                                 Optional Save As Boolean = False)

        If Ctrl.GetType().GetProperty("Checked") IsNot Nothing Then
            Dim chkd As System.Reflection.PropertyInfo = Ctrl.GetType().GetProperty("Checked")
            Dim chkdV As Boolean = CBool(chkd.GetValue(Ctrl))
            Dim ie As IEnumerable(Of XElement)
            ie = From el In MyControls.Elements
                    Where el.@name = Ctrl.Name
                    Select el Take 1

            Dim thisXML As XElement
            If ie.Count = 0 Then
                thisXML = <ctrl name=<%= Name %>></ctrl>
                MyControls.Add(thisXML)
            Else
                thisXML = ie(0)
            End If
            thisXML.@checked = chkdV.ToString
        End If
        If Save Then
            Try
                MyControls.Save(SavePath)
            Catch ex As Exception
                'todo
                ' Stop
            End Try
        End If
    End Sub
End Class

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

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