开发者

Adding element to XML using linq to XML

i have this piece of code which i use to add some elements:

  string xmlTarget = string.Format(@"<target name='{0}' type='{1}' layout='${{2}}'  />",
                                                new object[] { target.Name, target.Type, target.Layout });
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var xmlDoc = XElement.Load(configuration.FilePath);
            var nlog = xmlDoc.Elements("nlog");

            if (nlog.Count() == 0)
            {
                return false;
            }
            xmlDoc.Elements("nlog").First().Elements("targets").First().Add(xmlTarget);
            xmlDoc.Save(configuration.FilePath,SaveOptions.DisableFormatting);
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("nlog");
            return true;

it supposed to add a target to the xml , problem is it replace "<" with "&lt;" and ">" with "&gt;" which mess up my xml file.

how do i fix this ?

Not开发者_高级运维e please dont pay attention to nlog, i`m concerned about the linqtoxml problem.


You're currently adding a string. That will be added as content. If you want to add an element, you should parse it as such first:

XElement element = XElement.Parse(xmlTarget);

Or preferrably, construct it instead:

XElement element = new XElement("target",
    new XAttribute("type", target.Name),
    new XAttribute("type", target.Type),
    // It's not clear what your format string was trying to achieve here
    new XAttribute("layout", target.Layout));

Basically, if you find yourself using string manipulation to create XML and then parse it, you're doing it wrong. Use the API itself to construct XML-based objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜