• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 528
  • Last Modified:

remove an XML node with specific attribute from doc

I have a problem with my vb.net code where I need to remove a specific node with any attribute from a document where the value of the node is empty.
ie: <Inventory>
        <fruit id="apples">5</fruit>
        <fruit id="bananas"></fruit>
        <fruit id="oranges">12</fruit>
    <Inventory>
0
razingfools
Asked:
razingfools
  • 2
  • 2
1 Solution
 
nepaluzCommented:
try this

        Dim xTree As XElement = <Inventory>
                                    <fruit id="apples">5</fruit>
                                    <fruit id="bananas"></fruit>
                                    <fruit id="oranges">12</fruit>
                                </Inventory>
        Try
            For Each x As XElement In xTree.Descendants
                If String.IsNullOrEmpty(x.Value.ToString) Then x.Remove()
            Next
        Catch ex As Exception

        End Try

Open in new window

0
 
razingfoolsAuthor Commented:
Thanks for the quick response!
Sorry, but I posted this when i was rather sleepy and was trying not to complicate the issue too much, but I'm actually using a namespace manager as I'm having to do quite a bit of validating  and manipulation throughout the xml.  I tried to manipulate your suggestion, but without success.
My code actually goes something like this:

Dim _nsManager As New Xml.XmlNamespaceManager(_Document.NameTable)
Try
Dim _nodeList5 As Xml.XmlNodeList  = _Document.DocumentElement.SelectNodes(".//bz:fruit [@id='bananas']", _nsManager)
                  
For Each _node As Xml.XmlNode In _nodeList5
   If Len(_node.InnerText) = 0 Then
      _node.ParentNode.RemoveChild(_node)
    End If
Next
Catch
End Try      
0
 
nepaluzCommented:

1. How does _nodeList5 evaluate when you debug?
2. Once inside the For Each loop, does _node evaluate to anything?

try this then

            For Each _node As Xml.XmlNode In _nodeList5
                If String.IsNullOrEmpty(_node.Value.ToString) Then
                    _node.ParentNode.RemoveChild(_node)
                End If
            Next

Open in new window

0
 
razingfoolsAuthor Commented:
Thanks for the help!  Your suggestion was spot on.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now