根据您所展示的内容,首先我必须指出XML片段不是有效的XML。 data
节点未关闭。
假设这是一个有效的XML文档,它最终将取决于变量XMLDoc
的类型。
如果这是一个XDocument
,那么该代码片段应该工作,并且exists
的值将是true
。该文件包含一个名为root
的后代,它可能涉及其业务。
另一方面,如果这是一个XElement
,那么该代码段应该失败,并且exists
的值将是false
。 XMLDoc
变量已经指的是root
元素,显然没有任何后裔称为root
。
你应该然而,重写查询,也许更多的东西是这样的:
// please follow .NET naming conventions and use lowercase for local variables
XDocument xmlDoc = XDocument.Load(xmlFile);
// iterate over the `data` elements, not the `root` elements
bool exists = (from data in xmlDoc.Element("root").Elements("data")
where (string)data.Attribute("name") == "ID1"
select data).Any();
// using the cast is a personal style choice
// using `XAttribute.Value` is fine too in this case
什么是'XMLDoc'类型?它是'XDocument'还是它是'XElement'?这是你的实际XML吗?它不是有效的XML('data'节点没有关闭)。 – 2012-01-08 06:00:56
这只是一个XML片段。 – Rod 2012-01-08 06:06:48