0

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! :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
João Paulo
  • 41
  • 1
  • 6
  • 1
    Because `elementC` has a namespace. Please see https://stackoverflow.com/a/50783747/8951109 for reference... – Sebastian Hofmann Jun 18 '18 at 14:07
  • Yeah, but I need to specify the namespace, in other words I need to know the namespace value. Have some way to make it dynamic, using the XDocument.Element function? – João Paulo Jun 18 '18 at 14:26

1 Answers1

1
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.

Sebastian Hofmann
  • 1,440
  • 6
  • 15
  • 21