Adding element to XML using linq to XML

十年热恋 提交于 2019-12-11 10:21:50

问题


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:


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.



来源:https://stackoverflow.com/questions/7554602/adding-element-to-xml-using-linq-to-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!