posts - 76, comments - 26, trackbacks - 0

Using XPath to select nodes with a missing attribute

The only thing worse than my XPath skills are my RegEx skills.  I don’t use XPath all that much these days, but today I needed to.  It took me a while to find a code sample that does this.  After a playing a bit with SnippetCompiler, I found the solution:

 

StringBuilder builder = new StringBuilder();
builder.AppendLine("<foo>");
builder.AppendLine("<bar baz=\"a\">1</bar>");
builder.AppendLine("<bar>2</bar>");
builder.AppendLine("<bar baz=\"b\">3</bar>");
builder.AppendLine("<bar>4</bar>");
builder.AppendLine("<bar baz=\"c\">5</bar>");
builder.AppendLine("</foo>");

XmlDocument doc = new XmlDocument();
doc.LoadXml(builder.ToString());

XmlNodeList nodes = doc.SelectNodes("//foo/bar[not(@baz)]");

if ( nodes == null )
{
    WL("nodes was null");
}
else
{
    foreach ( XmlNode node in nodes )
    {
        WL("Node: " + node.InnerText);
    }
}

 

 

image 

image

Print | posted on Thursday, January 14, 2010 8:05 PM | Filed Under [ cheatsheet development ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 6 and 1 and type the answer here:

Powered by: