【问题标题】:Get Count of XML content Linq to XML获取 XML 内容的计数 Linq to XML
【发布时间】:2014-06-10 13:17:47
【问题描述】:
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")

如果没有找到记录,它将继续创建具有以下内容的文件

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

所以我明白为什么并且为了避免它我已经尝试过

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

但是当保存函数在调试器中命中时,所有的计数都大于 0.... 请注意 For Each 循环总是返回至少一个客户,然后受 If 函数的限制。那么我怎样才能获得在 XML 中创建的记录数,所以如果 0 没有创建文件,否则它会创建?我已经搜索过这个,但我认为它应该很简单,我认为我错过了这个难题的一部分。

【问题讨论】:

    标签: vb.net linq-to-xml


    【解决方案1】:

    MyXdoc 将始终有一个子节点:&lt;Customers&gt;,即根节点。

    您要检查&lt;Customers&gt; 节点本身是否有子节点:

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

    或者简单地使用一个标志:

    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 
    

    【讨论】:

    • 我知道我可以做后者,但作为学习曲线,我想知道如何使用 Linq to XML - 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多