João Paulo
João Paulo

Reputation: 41

XDocument not finding specific element

I have a custom function that gets an element by name.

public static XElement GetElement(this XElement element, string elementName)
{
    if (!element.HasElements)
        throw new HasNoElementsException("");

    return element.Element(element.GetDefaultNamespace() + elementName) ?? 
        throw new ElementNotFoundException("");
}

The function works normally, but I have a problem with one specific xml file exemplified here:

<?xml version="1.0" encoding="ISO-8859-1"?>
<elementA xmlns="http://www.link1.com.br">
    <elementB>
        ...other elements
    </elementB>
    <elementC xmlns="http://www.link2.com.br" schemaLocation="http://www.link1.com.br file.xsd">
        <elementD>
            ...other elements
        </elementD>
    </elementC>
</elementA>

When I try to get the elementB in the xml, it works, but when I try to get the elementC the ElementNotFoundException is thrown.

Sorry for my bad English, brazilian here! :)

Upvotes: 0

Views: 207

Answers (1)

Sebastian Hofmann
Sebastian Hofmann

Reputation: 1438

public static XElement GetElement(this XElement element, string elementName)
{
    if (!element.HasElements)
        throw new HasNoElementsException("");

    return element.Elements().FirstOrDefault(e => e.Name.LocalName.Equals(elementName)) ??
        throw new ElementNotFoundException("");
}

This would be a solution which gets the first element with the specified name without needing its default namespace.

Upvotes: 1

Related Questions