Computer
Computer

Reputation: 2227

Get Count of XML content Linq to XML

Dim MyXDoc As XDocument = <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customers> </Customers>

            For Each cust As Customer In Customers
              If cust.Name = "Bob"
                    MyXDoc.Root.Add(<Customer....
                                         </Customer>)
              End If
            Next

    MyXDoc.Save("C:\FileXML.xml")

If no records are found it continues to create a file with the below content

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Customers></Customers>

So i understand why and to avoid it i have tried

If MyXdoc.Nodes.Count > 0 
MyXDoc.Save("C:\FileXML.xml")
End If

If MyDoc.Elements.Count > 0
MyXDoc.Save("C:\FileXML.xml")
End If

If MyDoc.Descendants.Count > 0 
MyXDoc.Save("C:\FileXML.xml")
End If

but all have a count above 0 as the save function hits in the debugger.... Please note the For Each loop always returns at least one customer which is then limited by the If function. So how could i get the count of records that are being created in the XML so if 0 no file is created otherwise it does? Ive searched around on this but as easy as i thought it should be i think im missing a piece of this puzzle.

Upvotes: 1

Views: 72

Answers (1)

sloth
sloth

Reputation: 101052

MyXdoc will always have a child node: <Customers>, the root node.

You want to check if the <Customers> node itself has child nodes:

If MyXDoc.<Customers>.Nodes.Any() Then
    MyXDoc.Save("C:\FileXML.xml")
End If

or simply use a flag:

Dim added = False
For Each cust As Customer In Customers
    If cust.Name = "Bob"
        MyXDoc.Root.Add(<Customer></Customer>)
        added = True
    End If
Next
If added Then
    MyXDoc.Save("C:\FileXML.xml")
End If 

Upvotes: 1

Related Questions