Pregunta

I want to check if a xml element with a certain value exists. Found many examples but these all have multiple child nodes but mine doesn't.

This is my XML:

<?xml version='1.0' encoding='UTF-8'?>
<data>
<cocktail>1</cocktail>
<cocktail>2</cocktail>
<cocktail>3</cocktail>
</data>

C#: (the variable name contains the value for which I want to check whether it exists or not)

XDocument doc = XDocument.Load(stream, LoadOptions.None);
bool b = (from cocktail in doc.Root.Elements("data") 
     where (bool)cocktail.Name.Equals(name) select cocktail).Any();
¿Fue útil?

Solución

Your question isn't completely clear, but assuming you want to know whether the root element has a <cocktail> child with value name, this would work:

bool exists = doc.Root.Elements("cocktail")
    .Where(element => element.Value == name)
    .Any();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top