[英]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.