我有以下名为 testFix.fix 的 XML 文档
<WriteFixedWidth Type="extract">
<Position Start="1" Length="15" Name="Field1" />
<Position Start="16" Length="8" Name="Field2" />
<Position Start="24" Length="10" Name="Field3" />
</WriteFixedWidth>
还有下面的代码
public void readXML()
{
XDocument loaded = XDocument.Load(@"testSpec.xml");
var q = from c in loaded.Descendants("WriteFixedWidth").Elements("Position")
where c.Parent.Attribute("Type").ToString() == "Extract"
select new
{
Start = c.Attribute("Start").Value,
Length = c.Attribute("Length").Value,
Name = c.Attribute("Name").Value
};
foreach (var field in q)
Console.WriteLine("Name is {0}, Start is {1}, Length is {2}", field.Name, field.Start, field.Length);
}
如果删除 where 子句,我将按预期获得此 XML 文档中的所有字段。但是,对于不同的操作,我会有不同的“类型”属性。如何过滤来自父节点的数据?最好将其视为一个查询而不是构建两个查询。
最佳答案
访问属性时,需要使用Value
属性,而不是ToString()
。
var q = from c in loaded.Descendants("WriteFixedWidth").Elements("Position")
where c.Parent.Attribute("Type").Value == "extract"
select new
{
Start = c.Attribute("Start").Value,
Length = c.Attribute("Length").Value,
Name = c.Attribute("Name").Value
};
(另请注意,“extract”在您的示例中为小写,但在您的查询中为大写)
关于c# - 查询 parent.attribute 等于 LINQ to XML 中的某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4696519/