中的XDocument放置在树视图与另一个的XElement

问题描述:

我有一个简单XMLFILE替换元件和被放置在树视图中的XDocument放置在树视图与另一个的XElement

<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节点) 请帮我解决这个问题。

+2

为什么要混合使用LINQ to XML和“旧”DOM模型?你真的要吗?它很容易就不会...... –

谢谢你,我所有的解决方案。

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