开发者

Checking for solo nodes in LINQ to XML

开发者 https://www.devze.com 2023-02-04 10:54 出处:网络
How do I determine if a tag开发者_StackOverflow中文版 is of this format: <Closed /> in Linq To XML?You can use the XElement.IsEmpty property. Be aware of what IsEmpty checks for as defined by th

How do I determine if a tag开发者_StackOverflow中文版 is of this format: <Closed /> in Linq To XML?


You can use the XElement.IsEmpty property. Be aware of what IsEmpty checks for as defined by the note on the linked MSDN page:

Note that an element that contains a start and end tag with no content between the tags is not considered to be an empty element. It has content with no length. Only an element that contains only a start tag, and is expressed as a terminated empty element, is considered to be empty.

To illustrate, consider the following example:

var xml = XElement.Parse(@"<root>
    <pair>foo</pair>
    <pair></pair>
    <single id=""42"" />
    <single />
</root>");

foreach (var element in xml.Elements())
{
    Console.WriteLine("{0}: {1}", element.IsEmpty, element);
}

// False: <pair>foo</pair>
// False: <pair></pair>
// True: <single id="42" />
// True: <single />

If you want to check that a node IsEmpty and also has no attributes, add a check for element.Attributes().Any() being false.

0

精彩评论

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

关注公众号