我的代码遇到了一些麻烦。当我运行它时,它仅删除第一组xml节点。如果我尝试删除第二个或第三个,则不会删除任何内容。我也在阅读xml文件。我认为我的代码无法正常循环。我希望我的代码循环遍历所有子节点,并删除在文本框中输入的子节点。是否有人知道发生这种情况的原因。
Sub del()
Dim a As Variant
Dim s As Variant
Dim r As Range
Dim l As Long
a = Array("*abc*", "*def*", "efg*", "abcdef*hi")
Set r = Range("a1:a20")
For l = r.Rows.Count To 1 Step -1
For Each s In a
If r.Cells(l, 1).Value Like s Then
Rows(l).EntireRow.Delete
Exit For
End If
Next s
Next l
End Sub
xml代码示例:(注意:我可能有数百行xml)
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim doc As New XmlDocument()
doc.Load(path & FileXml)
Dim Nodes = doc.SelectNodes("//TicketNumber")
For Each elem As XmlElement In Nodes
Console.WriteLine(elem.InnerText)
If elem.InnerText = TextBox1.Text Then
elem.ParentNode.ParentNode.RemoveChild(elem.ParentNode)
MessageBox.Show("Element Deleted! ") '& TicketNumber.ToString)
Exit For
End If
Next
doc.Save(path & FileXml)
End Sub
完整代码
<?xml version="1.0" encoding="us-ascii" standalone="yes"?>
<sales_audit_xml>
<DataTable>
<TicketNumber>0145191647504</TicketNumber>
<Total_Amt>11.39</Total_Amt>
<Total_Taxes>0.00</Total_Taxes>
<Code>SUN1</Code>
</DataTable>
<DataTable>
<TicketNumber>0145191647505</TicketNumber>
<Total_Amt>11.39</Total_Amt>
<Total_Taxes>0.00</Total_Taxes>
<Code>SUN1</Code>
</DataTable>
<DataTable>
<TicketNumber>0145192428666</TicketNumber>
<Total_Amt>13.64</Total_Amt>
<Total_Taxes>0.00</Total_Taxes>
<Code>SUN1</Code>
</DataTable>
</sales_audit_xml>
结束班级
第一个按钮用于读取txt文件,第二个按钮用于模式验证器,第三个按钮用于删除元素。我还有一个文本框,用于删除机票号码
答案 0 :(得分:0)
我个人更喜欢使用在.Net 3.5中实现的XDocument类。
鉴于:
我编写了类似的代码,只删除了我选择的带有字符串“ deleteme”的行,该字符串可以是您的“ TextBox1.Text”。
如我所写,它将删除每个包含给定字符串的字符串。如果确定只有一个具有给定字符串的条目,则可以像在示例中一样输入“ Exit For”命令。
Dim tst_xml_path = "MyPath"
Dim deleteme As String = ("0145191647505")
Dim doc As New XDocument()
doc = XDocument.Load(tst_xml_path & "tst.xml")
For Each elem In doc.<sales_audit_xml>.<DataTable>
If elem.<TicketNumber>.Value = deleteme Then
MsgBox("Element " & elem.<TicketNumber>.Value & " deleted!")
elem.<TicketNumber>.Remove()
End If
Next
Console.WriteLine(doc.ToString)
doc.Save(tst_xml_path & "tst.xml")
所以我尝试了以下修改的完整代码:
Public Sub Button5_Click() 'Removed the params to call the function easily.
Dim deleteme As String = ("01451947504") 'Debug Var for string comapre
Dim doc As New XmlDocument()
doc.Load(path & FileXml)
Dim Nodes = doc.SelectNodes("//TicketNumber")
For Each elem As XmlElement In Nodes
If elem.InnerText = deleteme Then
elem.ParentNode.ParentNode.RemoveChild(elem.ParentNode)
MsgBox("Element Deleted! ", MsgBoxStyle.Critical) '& TicketNumber.ToString) 'Edited the MessageBox
End If
Next
doc.Save(path & "ouput.xml") 'Edited the ouput file for debug purpose
End Sub
我只是在我的主要函数中这样调用它...
Dim Tst = New Form1
Tst.Button5_Click()
一切都很好。我可以删除您在示例XML文件中编写的所有3个数据表...