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.

1
  • 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).) Commented Sep 26, 2011 at 11:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.