如何在c#中使用XElement获取具有特定值的节点
本文关键字:节点 获取 XElement | 更新日期: 2023-09-27 18:26:32
我有以下xml代码,希望获取Shelters下值为"Loft"answers"Condos"的sheltertype以在Xelement中列出。
<Shelters>
<Shelter>
<ShelterType>Loft</ShelterType>
<Price>250/500</Price>
<Area>250/500</Area>
<ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
</Shelter>
<Shelter>
<ShelterType>TownHouse</ShelterType>
<Price>250/500</Price>
<Area>250/500</Area>
<ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
</Shelter>
<Shelter>
<ShelterType>Condos</ShelterType>
<Price>250/500</Price>
<Area>250/500</Area>
<ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
</Shelter>
<Shelter>
<ShelterType>apartment</ShelterType>
<Price>250/500</Price>
<Area>250/500</Area>
<ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
</Shelter>
---
</Shelters>
我尝试了Descendants,结果得到了空值。正在寻找林克与XElement的工作。请帮助。
我相信这会给您带来所需的结果。这是从另一篇文章中的一个例子中提取的,该文章针对您的问题进行了修改,LINQ阅读XML
XDocument xdoc = XDocument.Load("Data.xml");
var lv1s = from lv1 in xdoc.Descendants("Shelter")
select new
{
ShelterType = lv1.Element("ShelterType").Value
};
foreach (var lv in lv1s)
{
Console.WriteLine(lv.ShelterType);
}
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:'temp'test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> sheltertype = doc.Descendants("Shelter")
.Where(x => (x.Element("ShelterType").Value == "Loft") || (x.Element("ShelterType").Value == "Condos")).ToList();
}
}
}