1

我有以下 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 进行编辑后,并且在用户在条目中选择一个条目值后,加载一些文本框进行编辑。用户完成编辑后,我保存它。保存后,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");
                       }
4

1 回答 1

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);
于 2011-08-18T12:03:12.333 回答