使用linq to XML向XML添加元素 [英] Adding element to XML using linq to 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中添加目标,问题是它替换为<"加上"<
"和>"以及">
",弄乱了我的xml文件.
it supposed to add a target to the xml , problem is it replace "<" with "<
" and ">" with ">
" 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屋!