使用linq to XML向XML添加元素 [英] Adding element to XML using linq to XML

查看:139
本文介绍了使用linq to XML向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;

它应该向xml中添加目标,问题是它替换为<"加上"&lt;"和>"以及"&gt;",弄乱了我的xml文件.

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

我该如何解决?

注意,请不要关注nlog,我担心linqtoxml问题.

Note 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));

基本上,如果您发现自己使用字符串操作来创建XML,然后对其进行解析,则说明这样做是错误的.使用API​​本身来构造基于XML的对象.

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.

这篇关于使用linq to XML向XML添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆