如何使用XmlDocument删除具有属性的元素?

时间:2014-07-11 00:34:35

标签: xml vb.net

如何删除具有属性的元素?

我正在尝试删除:

  <User Name="1">
    <PrivateFtpAccountId-1>11111</PrivateFtpAccountId-1>
    <PrivatePassword-1>test1</PrivatePassword-1>
    <PublicFtpAccountId-1>22222</PublicFtpAccountId-1>
    <PublicPassword-1>test2</PublicPassword-1>
  </User>

从我的xml看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<Users>
  <User Name="1">
    <PrivateFtpAccountId-1>11111</PrivateFtpAccountId-1>
    <PrivatePassword-1>test1</PrivatePassword-1>
    <PublicFtpAccountId-1>22222</PublicFtpAccountId-1>
    <PublicPassword-1>test2</PublicPassword-1>
  </User>
  <User Name="2">
    <PrivateFtpAccountId-2>33333</PrivateFtpAccountId-2>
    <PrivatePassword-2>test3</PrivatePassword-2>
    <PublicFtpAccountId-2>44444</PublicFtpAccountId-2>
    <PublicPassword-2>test4</PublicPassword-2>
  </User>
</Users>

我明白了:

未处理的异常:System.Xml.XPath.XPathException:'/ Users / User Name =“1”'has  无效的令牌。

我的控制台应用代码是:

    Dim nodes As XmlNodeList
    Dim myXmlDocument As New XmlDocument()
    Dim strUser As String
    Dim bSucess As Boolean = False

    strUser = "User Name=""1"""

    myXmlDocument.Load("MyGoodXMLfordeleting.xml")

    nodes = myXmlDocument.SelectNodes("/Users/" & strUser)

    For Each node As XmlNode In nodes
        If node IsNot Nothing Then
            node.ParentNode.RemoveChild(node)
            myXmlDocument.Save("MyGoodXMLfordeleting.xml")
            bSucess = True
        End If
    Next

1 个答案:

答案 0 :(得分:0)

您的XPath查询无效。

尝试XPath查询,例如:

/Users/User[@Name='1']

XPath示例:

http://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx

相关问题