简体   繁体   中英

Replace element in xdocument placed in a treeview with another xelement

I have a simple xmlfile and that is placed in a treeview

 <bookstore xmlns="generic">
     <book genre="Book" >`
       <title>Book of Benjamin Franklin</title>
       <author>
         <first-name>Benson</first-name>
         <last-name>Frank</last-name>
      </author>
      <price>89.88</price> 
     </book>
     <book genre="autobiography">
        <title>The Autobiography of Benjamin Franklin</title> 
        <author>
           <first-name>Ben</first-name> 
           <middlename /> 
           <last-name>Franklin</last-name> 
        </author>
        <price>89.88</price> 
     </book>
   <book genre="novel" >
     <title>The Confidence Man</title> 
     <author>
       <first-name>John</first-name> 
       <last-name>Melville</last-name> 
     </author>
    <price>11.99</price> 
   </book>
</bookstore>

I want to replace (2nd element)

<book genre="autobiography" >
    <title>The Autobiography of Benjamin Franklin</title> 
    <author>
       <first-name>Ben</first-name> 
       <middlename /> 
       <last-name>Franklin</last-name> 
    </author>
    <price>89.88</price> 
 </book>

with an another element(that is edited and i have edited portion as a string)

<book genre="autobiography">
   <title>The Autobiography of Benjamin Franklin</title>
   <author>
     <first-name>Ben</first-name>
     <last-name>Franklin</last-name>
   </author>
   <price>89.88</price>
</book>

Code I used is here

            XElement XmlTree = XElement.Parse(text);//text contain edited portion
            XmlElement XMLE = (XmlElement)TreeV.SelectedItem;


            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(scd_file);

            XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
            xfrag.InnerXml = text;
            XmlDocumentFragment xfrag1 = xdoc.CreateDocumentFragment();
            xfrag1.InnerXml = XMLE.OuterXml;

            xdoc.ReplaceChild(xfrag, xfrag1);

But it shows error (xfrag1 is not a node of xdoc) please help me to solve this problem.

thank u all i got the solution.

  XmlElement XMLE = (XmlElement)TreeV.SelectedItem;// selection from treeview(TreeV) that we want to edit (2nd element)
  XmlDocument XD = new XmlDocument();
  XD.LoadXml(text);// text is edited part save as a string
  XmlNode root=XD.DocumentElement;
  XmlDocument xml = XMLE.ParentNode.OwnerDocument;
  XmlNode import= xml.ImportNode(root, true);
  XMLE.ParentNode.ReplaceChild(import, XMLE);
  xml.Save(scd_file); //scd_file path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM