Search code examples
xmllinq-to-xmlxml-namespacesxelement

select XElements with xmlns


How do you select an element with xmlns specified? I need to select Include/Fragment element. I've tried adding http://schemas.microsoft.com/wix/2006/wi before element names, but that doesn't work. In XmlDocument there was NamespaceManager functionality, but I don't see same stuff in XDocument. So how do I select an element with xmlns?

<Include xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment/>
</Include>

I've tried:

IEnumerable<XElement> Fragments = d.Element("Include").Elements("Fragment");

and

const string xmlns="http://schemas.microsoft.com/wix/2006/wi/";
IEnumerable<XElement> Fragments = d.Element(xmlns+"Include").Elements(xmlns+"Fragment");

Solution

  • You just need to make your xmlns variable a XNamespace (instead of just a string):

    XNamespace xmlns = "http://schemas.microsoft.com/wix/2006/wi";
    
    IEnumerable<XElement> Fragments = doc.Element(xmlns + "Include").Elements(xmlns + "Fragment");
    

    then it should work just fine!