Query an XDocument Query doesn't work when element/root has Namespace as atribute

后端 未结 1 370
广开言路
广开言路 2021-01-23 17:10

The problem is that I can not get any results if the node contains namespace/attribute. This is the code:

Dim xmlFromDisk = XDocument.Load(\"customers.xml\")
Dim         


        
相关标签:
1条回答
  • 2021-01-23 17:47

    Sure, so you need to specify the namespace as well. xmlns="..." indicates the default namespace for any unqualified descendant elements.

    I don't know how you'd do it in an XML literal in VB, but in C# you'd just write:

    XNamespace ns = "http://tempuri.org/";
    var ukCustomers = doc.Root
                         .Elements(ns + "Customer")
                         .Where(x => (string) x.Element(ns + "Country") == "UK");
    

    EDIT: This is the equivalent VB code as shown by Reflector and hacked around a bit by me:

    Dim ns As XNamespace = "http://tempuri.org/"
    Dim ukCustomers =
       (From x In doc.Root.Elements(DirectCast((ns + "Customer"), XName))
        Where (CStr(x.Element(ns + "Country")) = "UK")
        Select x)
    
    0 讨论(0)
提交回复
热议问题