开发者

How to overwrite nodes in an xml file?

开发者 https://www.devze.com 2023-03-29 03:45 出处:网络
I have the following XML file: <WindowEntries> <WindowEntry> <Name>maduranga</Name>

I have the following XML file:

<WindowEntries>
<WindowEntry>
  <Name>maduranga</Name>
  <Vie开发者_C百科w>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>

I developed a TreeView for that xml. After user selects one WindowEntry from the Treeview for editing and after user selects one entry value in entry load some Textbox for editing. After user finishes editing, I save it. After save, the xml file look like this:

<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>

but i want to overwrite "madurang" value with "newvalue". This is the code what I use for that edit.

     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");
                       }


Linq-XML is simple and powerful.

  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);
0

精彩评论

暂无评论...
验证码 换一张
取 消