2008-10-06 12 views
8

Załóżmy mamy ten xml:Czy istnieje sposób pobierania elementów przy użyciu tylko lokalnych nazw w zapytaniu Linq-to-XML?

<?xml version="1.0" encoding="UTF-8"?> 
<tns:RegistryResponse status="urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure" 
    xmlns:tns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" 
    xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0"> 
    <tns:RegistryErrorList highestSeverity=""> 
     <tns:RegistryError codeContext="XDSInvalidRequest - DcoumentId is not unique." 
      errorCode="XDSInvalidRequest" 
      severity="urn:oasis:names:tc:ebxml-regrep:ErrorSeverityType:Error"/> 
    </tns:RegistryErrorList> 
</tns:RegistryResponse> 

aby pobrać RegistryErrorList elementu, możemy zrobić

XDocument doc = XDocument.Load(<path to xml file>); 
XNamespace ns = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; 
XElement errorList = doc.Root.Elements(ns + "RegistryErrorList").SingleOrDefault(); 

ale nie podoba

XElement errorList = doc.Root.Elements("RegistryErrorList").SingleOrDefault(); 

Czy istnieje sposób, aby zrobić kwerendę bez przestrzeni nazw elementu. W zasadzie jest tam coś conceptially podobny do korzystania local-name() w XPath (tj // * [local-name() 'RegistryErrorList' =])

Odpowiedz

8
var q = from x in doc.Root.Elements() 
     where x.Name.LocalName=="RegistryErrorList" 
     select x; 

var errorList = q.SingleOrDefault(); 
2

W "metody" składni kwerendy wyglądałby na przykład:

XElement errorList = doc.Root.Elements().Where(o => o.Name.LocalName == "RegistryErrorList").SingleOrDefault(); 
0

Poniższe rozszerzenie zwróci kolekcję pasujących elementów z dowolnego poziomu XDocument (lub dowolnego XContainer).

 public static IEnumerable<XElement> GetElements(this XContainer doc, string elementName) 
    { 
     return doc.Descendants().Where(p => p.Name.LocalName == elementName); 
    } 

Twój kod będzie wyglądać następująco:

var errorList = doc.GetElements("RegistryErrorList").SingleOrDefault(); 
Powiązane problemy