Erica Stockwell-Alpert
Erica Stockwell-Alpert

Reputation: 4863

(String)XElement returning empty string even though XElement is not empty (C#)

I'm trying to get the image from an image tag in an XML file. The Image element gets passed to this function:

private Image GetImage(XElement element)
{
    var image = new Image();

    var elemString = (String)element;
    if (String.IsNullOrEmpty(elemString))
    {
        return image;
    }

    XElement imageElement = element.Element("img");
    if (imageElement != null)
    {
        image.Url = (String)imageElement.Attribute("src");
    }
    return image;
}

I need to have it check whether the element is empty, so that I don't try to get element.Element("img") on an empty string and get an error. However, all of my elements are returning empty; (String)element returns as "" even though my elements are not empty.

For example, one of my element objects looks like this:

<Image>
  <img src="/assets/0/206/207/76aa1e77-4d7f-474e-9b94-3250a60b887a.jpg?n=673" alt="jackerman" />
</Image>

But (String)element = "";

The same thing is happening for links, where (String)element on valid Links returns as an empty string.

private Link GetLink(XElement element)
{
    var link = new Link();

    if (String.IsNullOrEmpty((String)element))
    {
        return link;
    }

    XElement anchorElement = element.Element("a");
    if (anchorElement != null)
    {
        link.Url = (String)anchorElement.Attribute("href");
        link.Text = (String)anchorElement;
    }
    return link;
}

Why is (String)element returning empty, and if this doesn't work, how can I check whether 'element' is null/empty?

Upvotes: 0

Views: 462

Answers (1)

juharr
juharr

Reputation: 32296

You don't need to cast to string you are already checking if Element returns null, which is sufficient to determine if the sub-element exists.

private Image GetImage(XElement element)
{
    var image = new Image();

    XElement imageElement = element.Element("img");    
    if (imageElement != null)
    {
        image.Url = (String)imageElement.Attribute("src");
    }
    return image;
}

The reason casting to string is empty is because it will return the concatenated text of the element and the elements descendants, but your element and it's descendants does not contain any text. See the documentation for the explicit string cast for XElement here.

Upvotes: 2

Related Questions