简体   繁体   English

C#检查元素是否存在于xml where属性中

[英]C# check if element exists in xml where attribute

I need to check my XML document if a certain element exists with the name 我需要检查我的XML文档,如果名称中存在某个元素

channel-category 

where element attribute equals certain id 其中element属性等于某些id

channel id="X"

I have the following function but it's always returning false even though it does exist 我有以下函数,但即使确实存在,它总是返回false

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 这是我的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. 现在,该函数应该为id Channelname1返回true,而为id Channelname2返回false,但是对于它们两个都只是返回false,我不确定为什么。 Any thoughts? 有什么想法吗?

Do you have to use XDocument and Linq2Xml ? 您必须使用XDocument和Linq2Xml吗? How about using the XmlDocument class and XPath? 如何使用XmlDocument类和XPath?

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

        return doc.SelectSingleNode("//tv/channel[@id=" + channelname + "]/channel-category") != null;
    }

I agree with HaukurHaf , alternatively you could also write simple Linq statement as shown below. 我同意HaukurHaf ,或者您也可以编写简单的Linq语句,如下所示。

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 试试这个工作Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM