如果存在名称为
的特定元素,我需要检查我的XML文档channel-category
其中element属性等于某个id
channel id="X"
我有以下功能但它总是返回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;
}
这是我的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>
现在函数应该为id为Channelname1返回true,但对于id为Channelname2则返回false,但它只是为它们返回false并且我不确定原因。有什么想法吗?
答案 0 :(得分:1)
你必须使用XDocument和Linq2Xml吗? 如何使用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;
}
答案 1 :(得分:1)
我同意 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);
}
尝试这项工作Demo