2008-10-06 15 views
8

Asumamos que tenemos esta xml:¿Hay alguna manera de recuperar elementos utilizando solo nombres locales en una consulta 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> 

Para recuperar elemento RegistryErrorList, podemos hacer

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(); 

pero no de esta forma

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

¿Hay una manera de hacer la consulta sin el espacio de nombre del elemento. Básicamente hay algo conceptially similar al uso local-name() en XPath (es decir, // * [local-name() 'RegistryErrorList' =])

Respuesta

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

var errorList = q.SingleOrDefault(); 
2

En el "método" sintaxis de la consulta se vería como:

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

la siguiente extensión devolverá una colección de elementos de contrapartida de cualquier nivel de una XDocument (o cualquier XContainer).

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

Su código sería ahora el siguiente aspecto:

var errorList = doc.GetElements("RegistryErrorList").SingleOrDefault(); 
Cuestiones relacionadas