1

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 ?

Note please dont pay attention to nlog, i`m concerned about the linqtoxml problem.

Stacker
  • 8,157
  • 18
  • 73
  • 135
  • 1
    Quick note: there's an easy way to get us to not pay attention to particular parts of the code... trim them out of the post. (As an aside, using `if (!nlog.Any())` is better than using `if (nlog.Count() == 0)`.) – Jon Skeet Sep 26 '11 at 11:53

1 Answers1

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194