Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to retrieve elements using only local names in a Linq-to-XML query?

Tags:

linq-to-xml

Lets assume we have this 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>

To retrieve RegistryErrorList element, we can do

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

but not like this

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

Is there a way to do the query without the namespace of the element. Basicly is there something conceptially similiar to using local-name() in XPath (i.e. //*[local-name()='RegistryErrorList'])

like image 527
aogan Avatar asked Oct 06 '08 19:10

aogan


People also ask

What is created to retrieve data into XML using LINQ?

LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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

var errorList = q.SingleOrDefault();
like image 56
Mark Cidade Avatar answered Oct 12 '22 07:10

Mark Cidade


In the "method" syntax the query would look like:

XElement errorList = doc.Root.Elements().Where(o => o.Name.LocalName == "RegistryErrorList").SingleOrDefault();
like image 20
aogan Avatar answered Oct 12 '22 07:10

aogan