C# 如何在c中使用XElement获取具有特定值的节点#
我有下面的xml代码,并希望获取避难所下的sheltertype值“Loft”和“Condos”,以在Xelement中列出C# 如何在c中使用XElement获取具有特定值的节点#,c#,xml,linq,C#,Xml,Linq,我有下面的xml代码,并希望获取避难所下的sheltertype值“Loft”和“Condos”,以在Xelement中列出 <Shelters> <Shelter> <ShelterType>Loft</ShelterType> <Price>250/500</Price> <Area>250/5
<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>
阁楼
250/500
250/500
$250,000 / $500,000
联排别墅
250/500
250/500
$250,000 / $500,000
公寓
250/500
250/500
$250,000 / $500,000
公寓
250/500
250/500
$250,000 / $500,000
---
我尝试使用后代,得到了空值。正在寻找Linq和XElement一起工作。请帮忙。我相信这会给你想要的结果。这是从另一篇文章中的一个例子中提取出来的,这篇文章被修改为你的问题 试试这个
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();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
命名空间控制台应用程序1
{
班级计划
{
常量字符串文件名=@“c:\temp\test.xml”;
静态void Main(字符串[]参数)
{
XDocument doc=XDocument.Load(文件名);
列表sheltertype=文档子体(“避难所”)
其中(x=>(x.Element(“ShelterType”).Value==“Loft”)| |(x.Element(“ShelterType”).Value==“Condos”).ToList();
}
}
}
在XPATH
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();
}
}
}