我有类似的 xml 文件
<House>
<Name>some name</Name>
<Price>22223</Price>
</House>
我正在使用 XElement 加载文件并选择它的元素
XElement elem = XElement.Load(fileName);
var houseElements = from h in elem.Elements() select h;
问题是:如何访问文件中每个元素的值 我试过
model.Name = houseElements.Where(x => x.Name == "Name").Select(x => x.Value).ToString();
model.Price= Convert.ToInt16(houseElements.Where(x => x.Name == "Price").Select(x => x.Value));
但这行不通
最佳答案
Select
、Where
和其他 LINQ 方法返回 IEnumerable
(如集合),而不是单个项目。
这是因为可能有很多项目具有指定的名称。
但由于您确定只有一个项目,您可以像这样获取第一个项目(通过 the First()
method ):
var Name =
houseElements
.Where(x => x.Name == "Name")
.Select(x => x.Value)
.First();
var Price =
Convert.ToInt16(
houseElements
.Where(x => x.Name == "Price")
.Select(x => x.Value)
.First());
这是一个更好的代码版本:
var Name =
houseElements
.Elements("Name")
.First()
.Value;
var Price =
Convert.ToInt16(
houseElements
.Elements("Price")
.First()
.Value);
关于c# - 访问 xml 节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370115/