Ranga Sarin Ranga Sarin - 3 months ago 15
SQL Question

C# check if element exists in xml where attribute

I need to check my XML document if a certain element exists with the name

channel-category


where element attribute equals certain id

channel id="X"


I have the following function but it's always returning false even though it does exist

static bool exists(string channelname)
{
string path;
string xmlfile = "\\xmlfile.xml";
path = Environment.CurrentDirectory + xmlfile;
XDocument xmlDoc = XDocument.Load(path);

bool doesexists = (from data in xmlDoc.Element("tv").Elements("channel").Elements("channel-category")
where (string)data.Attribute("id") == channelname
select data).Any();
return doesexists;
}


here is an example of my xml

<tv info="blahblah">
<channel id="Channelname1">
<display-name lang="en">Channelname1</display-name>
<icon src="somelogo.png" />
<url>http://somelink.com</url>
<channel-category>SomeValue</channel-category>
</channel>
<channel id="Channelname2">
<display-name lang="en">Channelname2</display-name>
<icon src="somelogo.png" />
<url>http://somelink.com</url>
</channel>
</tv>


Now the function should return true for id Channelname1 but false for id Channelname2 but it's just returning false for both of them and I'm not sure why. Any thoughts?

Answer

I agree with HaukurHaf, alternatively you could also write simple Linq statement as shown below.

static bool exists(string channelname) 
{
    string path;
    string xmlfile = "\\xmlfile.xml";
    path = Environment.CurrentDirectory + xmlfile;
    XmlDocument doc = XmlDocument.Load(path);

     return (doc.Descendants("channel").Any(x => (string) x.Attribute("id") == channelname && x.Element("channel-category") != null);
}

Try this working Demo

Comments