开发者

Query where parent.attribute is equal to some value in LINQ to XML

I have the following XML document named testFix.fix

<WriteFixedWidth Type="extrac开发者_Python百科t">
  <Position Start="1" Length="15" Name="Field1" />
  <Position Start="16" Length="8" Name="Field2" />
  <Position Start="24" Length="10" Name="Field3" />
</WriteFixedWidth>

Also, the following code

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);
}

If I remove the where clause I get all of the fields in this XML document as expected. However I would have different "Type" attributes for different operations. How do I filter the data from the parent node? It would be nice to see this as one query rather than building two.


When accessing an attribute, you need to use the Value property, rather than 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
            };

(Also note that "extract" is lowercase in your sample, but uppercase in your query)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜