[英]How to add attributes to a Xelement
这是我插入 XElement 的代码
XDocument doc = XDocument.Load("Database.xml");
XElement root = new XElement("SCENE" , "SCENE_" + strSceneName);
var scenePath = doc.XPathSelectElement("//DATABASE");
scenePath.Add(root);
doc.Save("Database.xml");
元素是这样插入的
<SCENE>SCENE_ProjectedScore_Logo</SCENE>
这是必需的
<SCENE SCENE_NAME="SCENE_ProjectedScore_Logo"SCENE>
我需要在我的代码中做哪些更改才能实现此目的。
不要将第二个参数作为字符串传递给XElement
root
,而是使用 XElement class 中的SetAttributeValue()
function。
喜欢,
XDocument doc = XDocument.Load("Database.xml");
XElement root = new XElement("SCENE"); //Update instanciation of XElement
root.SetAttributeValue("SCENE_NAME", $"SCENE_{strSceneName}"); //Use this method to set attribute with value.
var scenePath = doc.XPathSelectElement("//DATABASE");
scenePath.Add(root);
doc.Save("Database.xml");
MSDN 文档: XElement.SetAttributeValue
XElement.SetAttributeValue()
优于使用 XAttribute 参数调用 XElement 构造函数的好处是:( 来自 MSDN)
此方法旨在简化将名称/值对列表作为一组属性进行维护的过程。
如果你更换
XElement root = new XElement("SCENE" , "SCENE_" + strSceneName);
和
XElement root = new XElement("SCENE" , new XAttribute("SCENE_NAME", "SCENE_" + strSceneName));
你应该有你想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.