简体   繁体   English

用另一个xelement替换放置在treeview中的xdocument中的元素

[英]Replace element in xdocument placed in a treeview with another xelement

I have a simple xmlfile and that is placed in a treeview 我有一个简单的xmlfile,并将其放在树视图中

 <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. 但是它显示错误(xfrag1不是xdoc的节点),请帮助我解决此问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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