c# - 使用 linq to XML 向 XML 添加元素

标签 c# linq-to-xml

我有这段代码,我用它来添加一些元素:

  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 添加一个目标,问题是它将“<”替换为“<”,将“>”替换为“>”,这很乱上传我的 xml 文件。

我该如何解决这个问题?

注意请不要关注nlog,我关心的是linqtoxml问题。

最佳答案

您当前正在添加一个字符串。这将作为内容添加。如果你想添加一个元素,你应该首先这样解析它:

XElement element = XElement.Parse(xmlTarget);

或者最好构造它:

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 的对象。

关于c# - 使用 linq to XML 向 XML 添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7554602/

相关文章:

c# - 如何打开具有只读保护的Excel文件?

c# - Linq 选择数据库中的对象存在字典键

c# - 运行时的 Linq To XSD

c# - 使用动态特性读取 XML 结构

c# - 我在这个 LINQ 语句中做错了什么?

wpf - XDocument 之上的 ViewModel

c# - 字符串到十六进制 int 数组?

c# - 如何从自己的集合中自动更新 ItemsSource?

c# - 如何在 asp.net mvc View 页面中显示人类可读的 xml

c# - 使用 SMO 更改逻辑数据库名称