使用LINQ删除XML元素

时间:2014-01-01 21:45:38

标签: xml vb.net linq

我编写了代码来添加条目,编辑不同的元素等,但我很难找到删除XML文件中条目的最佳方法。这不是缺乏研究。理想情况下,我想将用户名传递给过程并查询XML文件以获取用户名,然后删除userPc,userName和登录日期。计划是在表格关闭时运行程序。能帮我写一下这个方法吗?

XML

<?xml version="1.0" encoding="utf-8"?>
<user>
  <user>
    <userPC>assetTagNumber</userPC>
    <userName>userName</userName>
    <signInDate>01/01/2014 01:00:00</signInDate>
  </user>
  <user>
    <userPC>assetTagNumber2</userPC>
    <userName>userName2</userName>
    <signInDate>01/01/2014 01:00:01</signInDate>
  </user>
</user>

这是我当前的loginClass

Public Class loginClass

    Dim xmlCheckInFilePath As String = "\\itfs1\help_share$\ITCSToolBoxAdmin\AppAdmin\User_CheckIn\user.xml"
    Dim asset As String = Environment.MachineName
    Dim user As String = Environment.UserName
    Dim signInDate As String = DateTime.Now

    Public Sub loginToXmlFile()
        Try
            runDupeCheckQuery()
        Catch ex As Exception
            MessageBox.Show("Unable to run DupeCheckQuery in login class.", "loginClass", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub runDupeCheckQuery()
        Dim doc As XDocument = XDocument.Load(xmlCheckInFilePath)
        Dim appQuery = _
            From c In doc.<user>.<user> _
            Select c.<userName>
        For Each result In appQuery
            If result.Value = user Then
                Exit Sub
            End If
        Next
        addEntry()
    End Sub

    Private Sub addEntry()
        Dim doc As XDocument = XDocument.Load(xmlCheckInFilePath)
        Dim newEntry As XElement = _
        <user>
            <userPC><%= asset %></userPC>
            <userName><%= user %></userName>
            <signInDate><%= signInDate %></signInDate>
        </user>
        doc.Root.Add(newEntry)
        doc.Save(xmlCheckInFilePath)
    End Sub

    Public Sub removeEntry()

    End Sub

End Class

1 个答案:

答案 0 :(得分:3)

XNode.Remove方法,它从当前父节点中删除节点。

我没有测试过代码,但至少应该让您知道如何解决问题。

Public Sub removeEntry()

    Dim doc As XDocument = XDocument.Load(xmlCheckInFilePath)

    Dim userEntry As XElement = doc.<user>.<user>.FirstOrDefault(Function(u) u.<userName>.Value = user)

    If userEntry IsNot Nothing Then userEntry.Remove()

    doc.Save(xmlCheckInFilePath)

End Sub