views:

71

answers:

1

I am trying to write a app.config / web.config error correcting app that will audit our developers applications for incorrect environment settings. I am using Linq to XML to accomplish this and I am hitting a snag.

var query =
    from el in doc.Descendants().Element("SMTPHost")
    select el;

foreach (XElement host in query)
{
    if (Regex.IsMatch(el.Value, "mail.mycompany.com")
    {
        el.Value = Regex.Replace(el.Value, 
            "mail.mycompany.com", "devmail.mycompany.com");

    }
}

When I run this it concatinates all the child text values for one of the ancestor nodes of the correct element and removes all the child elements.

Is there a better way to do this sort of thing?

Thanks

+2  A: 

Firstly, I think your use of regular expressions is unnecessary here. Are you aware that will match "mailxmycompanyxcom" because of how dots are matched? Using String.Contains and String.Replace. Of course, if your real code uses genuine patterns, that's a different matter.

Anyway, on to the issue. It sounds to me like you're only interested in handling a single child node at a time - is that correct? If so, use:

var query =  doc.Descendants()
                .Element("SMTPHost")
                .DescendantNodes()
                .OfType<XText>();

foreach (XText textNode in query)
{
    textNode.Value = textNode.Value.Replace("mail.mycompany.com", 
                                            "devmail.mycompany.com");
}
Jon Skeet
You nailed it thanks!
Jeremy E