【问题标题】:How do I delete an element that has an attribute using XmlDocument?如何使用 XmlDocument 删除具有属性的元素?
【发布时间】:2014-09-01 12:43:26
【问题描述】:

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

我正在尝试删除:

  <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

【问题讨论】:

    标签: xml vb.net


    【解决方案1】:

    您的 XPath 查询无效。

    尝试 XPath 查询,例如:

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

    XPath 示例在这里:

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

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2011-10-23
      • 2011-01-11
      • 2017-08-10
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      相关资源
      最近更新 更多