tags:

views:

80

answers:

1

Hey guys,

I'm trying to get all nodes from an XElement that actually has a value, currently I'm using this code:

var nodes = from node in elem.Nodes()
            where node.NodeType == XmlNodeType.Element &&
                  ((XElement) node).Value.Length >  0
            select node;

Is there a build in operator to do this operation?

Thanks

+1  A: 

I don't believe there's anything like this built in. Are you sure you want to include elements that have subelements though? For example:

XElement e = new XElement("Foo", new XElement("Bar"));
Console.WriteLine(e);
Console.WriteLine(e.Value.Length);

This will print:

<Foo>
  <Bar />
</Foo>
0

... so Foo would be included as an "empty" node even though it contains another element. Is that definitely what you're after?

Jon Skeet
No I don't, I only want the non empty leaf nodes of the passed element.Will this do the job?var e = from node in elem.Elements() where !node.HasElements
Arjor
@Arjor: You might also want to think about attributes... you might want to test for !element.DescendantNodes().Any()
Jon Skeet