使用 linq to XML 添加元素到 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问题。
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 "<
" and ">" with ">
" 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您当前正在添加一个字符串。这将作为内容添加。如果你想添加一个元素,你应该首先这样解析它:
或者更好地,构造它:
基本上,如果你发现自己使用字符串操作来创建XML然后解析它,那么你就是做错了。使用 API 本身构建基于 XML 的对象。
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:
Or preferrably, construct it instead:
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.