开发者

Updating Linq to XML element values concatenation issues

I am trying to write a app.config / web.config error correcting app which 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 =开发者_如何学JAVA Regex.Replace(el.Value, 
            "mail.mycompany.com", "devmail.mycompany.com");

    }
}

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

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

Thanks!


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");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜