将放置在树视图中的xdocument中的元素替换为另一个xelement

时间:2012-09-25 11:17:59

标签: c# wpf linq-to-xml

我有一个简单的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>

我想替换(第二个元素)

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

我使用的代码在这里

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

但它显示错误(xfrag1不是xdoc的节点)  请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

谢谢你,我得到了解决方案。

  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