first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

LINQ to XML: The Equivalent of XPath Assertions; Basic Validation without XSD (schema)

/* using System; using System.Linq; using System.Xml.Linq; */

string xml = @" <root> <one>this one</one> <two>this two</two> <three> this one <three_5>and a half</three_5> </three> </root> ";

XDocument document = XDocument.Parse( xml );

var assertions = from n in document.Descendants( "root" )

select new
{
    HasOne = n.Element( &quot;one&quot; ),
    HasTwo = n.Element( &quot;two&quot; ),
    HasThree = n.Element( &quot;three&quot; ),
    HasTen = n.Element( &quot;ten&quot; )
};

//Verify that there is one root element: if ( assertions.Count() == 1 ) { var test = assertions.First();

Console.WriteLine( test.HasOne != null );
Console.WriteLine( test.HasTwo != null );

//Search for nested element:
if ( test.HasThree != null )
{
    Console.WriteLine( test.HasThree.Element( &quot;three_5&quot; ) != null );
}

Console.WriteLine( test.HasTen != null );

}

/*

Console output:

True True True False

*/

mod date: 2008-03-31T19:11:15.000Z