我有一個如下所示的 xml 檔案:
<Configuration>
<Elements>
<Element>
<Value1>7</Value1>
</Element>
<Element>
<Value1>3</Value1>
</Element>
</Elements>
</Configuration>
我現在想在每個元素之上添加一個值元素,這樣最后 xml 看起來像這樣:
<Configuration>
<Elements>
<Element>
<Value0>17</Value0>
<Value1>7</Value1>
</Element>
<Element>
<Value0>13</Value0>
<Value1>3</Value1>
</Element>
</Elements>
</Configuration>
我在 c# 中嘗試了以下內容:
XmlDocument doc = new XmlDocument();
doc.Load("config.xml");
XmlElement newelem = doc.CreateElement("Value0");
newelem.InnerText = newValue;
foreach (XmlNode node in doc.GetElementsByTagName("Element"))
{
node.InsertBefore(newelem, node.FirstChild);
}
這將添加新值,但僅添加到一個元素。我該怎么做才能將其添加到每個元素中?也許有一種完全不同的方法。我希望有人能理解我在嘗試什么,在此先感謝!
uj5u.com熱心網友回復:
在 for 回圈中創建元素。這是一些使用 XPath 的作業代碼。
foreach( XmlElement ndNode in xml.SelectNodes( "//Elements/Element")) {
XmlElement newelem = xml.CreateElement("Value0");
newelem.InnerText = "test";
ndNode.InsertBefore(newelem, ndNode.FirstChild);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406583.html
標籤:
下一篇:區分大小寫的名稱檢查器
