我的XML为:
<CONFIGURATION NAME="HDD">
<DECLARATION NAME="1ST_HDD_SATA">
<INSTANCE>
<PROPERTY NAME="ControllerPosition" CHECKPOSITION="true">
<INDEX>
<VALUE>0</VALUE>
<VALUE STEP="1">Std.flg</VALUE>
<VALUE STEP="2">Sas.flg</VALUE>
<VALUE STEP="-1">eS.flg</VALUE>`
<CONFIGURATION NAME="HDD">
<DECLARATION NAME="1ST_HDD_SATA">
<INSTANCE>
<PROPERTY NAME="ControllerPosition" CHECKPOSITION="true">
<INDEX>
<VALUE>0</VALUE>
<VALUE STEP="1">Std_Ctrl.flg</VALUE>
<VALUE STEP="2">Sas_Card.flg</VALUE>
<VALUE STEP="-1">eSAS1.flg</VALUE>
</INDEX>
<INDEX>
<VALUE>0</VALUE>
</INDEX>
</PROPERTY>
</INSTANCE>
</DECLARATION>
</CONFIGURATION>
使用LINQ获取值并显示Textbox中的所有元素,仅显示VALUE元素。
var hdd= from n1 in x.Elements("DECLARATION") where 1.Attribute("NAME").Value.Trim() == "1ST_HDD_SATA_Position" select n1.Elements("INSTANCE").Elements("PROPERTY").Elements("INDEX").Elements("VALUE");
然后更新文本框以包含VALUE元素的新值。例如,假设我将其更新为某个字符串。
foreach (IEnumerable<XElement> elList in hdd)
foreach (XElement el in elList)
{
el.ReplaceNodes("string");
el.Save(m);
}
这不是假设用更新保存我的xml文件吗?
答案 0 :(得分:3)
您的代码存在许多问题,首先是您发布了无效的XML。假设你的XML是这样的:
<CONFIGURATION NAME="HDD">
<DECLARATION NAME="1ST_HDD_SATA">
<INSTANCE>
<PROPERTY NAME="ControllerPosition" CHECKPOSITION="true">
<INDEX>
<VALUE>0</VALUE>
<VALUE STEP="1">Std.flg</VALUE>
<VALUE STEP="2">Sas.flg</VALUE>
<VALUE STEP="-1">eS.flg</VALUE>
</INDEX>
</PROPERTY>
</INSTANCE>
</DECLARATION>
</CONFIGURATION>
然后以下代码有效:
var doc = XDocument.Load("Configuration.xml");
var hdd = from n1 in doc.Elements("CONFIGURATION").Elements("DECLARATION")
let nameAttribute = n1.Attribute("NAME")
where nameAttribute != null && nameAttribute.Value.Trim() == "1ST_HDD_SATA"
select n1.Elements("INSTANCE")
.Elements("PROPERTY")
.Elements("INDEX")
.Elements("VALUE");
foreach (var elList in hdd)
foreach (var el in elList)
{
el.ReplaceNodes("string");
}
doc.Save("Configuration.xml");