C#IEnumerable<;XElement>;-如何对“Xpath”进行筛选;根“;?
在C#中,我有一个元素的IEnumerable。所有元素的名称相同,但类型不同。我想对每个XElement的“根”元素执行一个“xpath过滤器” 示例XML:C#IEnumerable<;XElement>;-如何对“Xpath”进行筛选;根“;?,c#,xpath,linq-to-xml,C#,Xpath,Linq To Xml,在C#中,我有一个元素的IEnumerable。所有元素的名称相同,但类型不同。我想对每个XElement的“根”元素执行一个“xpath过滤器” 示例XML: <xml> <Location> <Type>Airport</Type> <Buildings></Buildings> </Location> <Location>
<xml>
<Location>
<Type>Airport</Type>
<Buildings></Buildings>
</Location>
<Location>
<Type>Mine</Type>
<Buildings></Buildings>
</Location>
<Location>
<Type>Airport</Type>
<Buildings></Buildings>
</Location>
</xml>
我需要的是获取位置/类型为“机场”的所有建筑物。我想做的事情是:
elements.SelectMany(el => el.XPathSelectElements(".[Type = 'Airport']/Buildings/Building"));
但是,我无法理解XElement(即“.[Type”部分)的“根”处过滤的xpath语法
我能做的是:
元素。其中(loc=>loc.Element(“Type”)。Value==“Airport”)
var buildings = xml.XPathSelectElements("//xml/Location[Type=\"Airport\"]/Buildings");
例如:
string xmlString =
@"<xml>
<Location>
<Type>Airport</Type>
<Buildings>First airport buildings</Buildings>
</Location>
<Type>Mine</Type>
<Buildings>Mine buildings</Buildings>
<Location>
<Type>Airport</Type>
<Buildings>Second airport buildings</Buildings>
</Location>
</xml>";
XDocument xml = XDocument.Parse(xmlString);
var buildings =
xml.XPathSelectElements("//xml/Location[Type=\"Airport\"]/Buildings");
foreach (var b in buildings)
{
Console.WriteLine(b.Value);
}
好吧,我想要的似乎不可能。因此,我创建了一个“假根”元素,添加了我的XElement集合,并使用了xpath:
var airportBlgs = new XElement("root", locations)
.XPathSelectElements( "./Location[Type='Airport']/Building" );
伪根表示我不必使用“/”,因为它太宽了。很遗憾,仅使用xpath无法做到这一点。是否缺少
或位置嵌套?不是在我的电脑中,而是在你的“我想做”中,尝试将类型='Airport'
替换为类型/文本()='Airport'
。如果正确,请告诉我,我会提供答案。@Fabio你是对的,我缺少结束标记,它们不应该嵌套。@Richardissimo:“[Type/text()='Airport']”results in有一个无效的标记;“/[Type/text()='Airport']”和“[Type/text()='Airport']”result in expression必须计算到一个节点集”./Type/text()=“Airport”导致*意外类型System.Boolean(更接近!).知道我在哪里弄乱了语法吗?@emery.noel,如果你需要处理大量数据、名称空间和比这里发布的更复杂的结构,请编辑你的问题并提及这些细节。谢谢,但我只有XElement的集合,而不是整个文档。将元素加载到根XElement将起作用,我认为它实际上比XDocument更好。此外,我正在处理多组嵌套/重复的元素,因此“/”可能有效,也可能无效,这取决于将返回的(未知)XML。
First airport buildings
Second airport buildings
var airportBlgs = new XElement("root", locations)
.XPathSelectElements( "./Location[Type='Airport']/Building" );