我有以下XML文件:
<WindowEntries>
<WindowEntry>
<Name>maduranga</Name>
<View>TRN_UNIT</View>
<LU>TrnUnit</LU>
<DefaultWindowText />
<Flags>0</Flags>
</WindowEntry>
<WindowEntry>
<Name>tbwBrandOverView</Name>
<View>TRN_BRAND</View>
<LU>TrnBrand</LU>
<DefaultWindowText />
<Flags>0</Flags>
</WindowEntry>
<WindowEntries>
我为该xml开发了一个TreeView。用户从Treeview中选择一个WindowEntry进行编辑,并在用户在条目中选择一个条目值后加载一些Textbox进行编辑。用户完成编辑后,我保存。保存后,xml文件如下所示:
<WindowEntries>
<WindowEntry>
<Name>maduranga</Name>
<View>maduranga</View>
<LU>maduranga</LU>
<Flags>maduranga</Flags>
</WindowEntry>
<WindowEntry>
<Name>tbwBrandOverView</Name>
<View>TRN_BRAND</View>
<LU>TrnBrand</LU>
<Flags>0</Flags>
</WindowEntry>
**<WindowEntry>
<Name>newvalue</Name>
<View>newvalue</View>
<LU>newvalue</LU>
<Flags>newvalue</Flags>
</WindowEntry>**
<WindowEntries>
但我想用“newvalue”覆盖“madurang”值。 这是我用于编辑的代码。
XmlTextReader reader = new XmlTextReader("component.xml");
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode currNode;
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
try
{
string path3 = treeView1.SelectedNode.FullPath.ToString();
docFrag.InnerXml = "<WindowEntry>" +
"<Name>" + textBox7.Text + "</Name>" +
"<LU>" + textBox8.Text + "</LU>" +
"<View>" + textBox9.Text + "</View>" +
"<Flags>" + textBox10.Text + "</Flags>" +
"<OverrideDefaultHome>" + textBox11.Text + "</OverrideDefaultHome>" +
"<AssociatedHomepage>" + textBox12.Text + "</AssociatedHomepage>" +
"</WindowEntry>";
currNode = doc.SelectSingleNode("Component/WindowEntries");
currNode.AppendChild(docFrag);
doc.Save("component.xml");
}
答案 0 :(得分:0)
Linq-XML简单而强大。
filename = @"c:\path\sample.xml";
XDocument doc = XDocument.Load(filename);
var result = (from node in doc.Descendants("WindowEntry")
where node.Element("Name").Value == "maduranga"
select node.Element("Name")).ToList();
if(result.Count!=0)
result[0].Value = "NewValue";
doc.Save(filename);