首页 » 编程设计

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

2024年02月23日20开发

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

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


阅读延展