日期:2014-05-19  浏览次数:20416 次

asp.net 追加 xml文件时 报错
我重写时     没问题...

CheckBox   checkbox;
XmlDocument   newdom   =   new   XmlDocument();
XmlElement   newroot   =   newdom.CreateElement( "roles ");
foreach(DataGridItem       dgc       in       this.DataGrid1.Items)      
{
checkbox   =   (CheckBox)this.DataGrid1.Items[dgc.ItemIndex].FindControl( "CheckBox1 ");
if(((CheckBox)dgc.FindControl( "CheckBox1 ")).Checked==true)      
{    
XmlElement   role   =   newdom.CreateElement( "role ");
XmlElement   child   =   newdom.CreateElement( "param ");
child.SetAttribute( "name ", "rolename ");
child.SetAttribute( "value ",dgc.Cells[1].Text);
role.AppendChild(child);
newroot.AppendChild(role);
}    
}    
if(File.Exists(Server.MapPath( "xml\\roleuser.xml ")))
{
XmlDocument   docxml   =   new   XmlDocument();
File.AppendText(Server.MapPath( "xml\\roleuser.xml "));
            //File.OpenWrite(Server.MapPath( "xml\\roleuser.xml "));
docxml.AppendChild(newroot);
docxml.Save(Server.MapPath( "xml\\roleuser.xml "));
}
else
{
XmlDeclaration   xde   =   newdom.CreateXmlDeclaration( "1.0 ", "UTF-8 ", " ");
newdom.AppendChild(xde);
newdom.AppendChild(newroot);
newdom.Save(Server.MapPath( "xml\\roleuser.xml "));
}

===================================================

当文件   不存在     创建的时候没有错     但是在追加的时候   他报错
“要插入的节点出自不同的文档上下文”

是因为它不知道   要插哪里么?


------解决方案--------------------
XmlElement newroot = newdom.CreateElement( "roles ");
应该是 dom.CreateElement( "roles ");

------解决方案--------------------
XmlElement child = xmldom.CreateElement( "param ");
child.SetAttribute( "name ", "rolename ");
child.SetAttribute( "value ",dgc.Cells[1].Text);

XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml=child.OutXml;

xmlroot .AppendChild(docFrag);

应该可以
------解决方案--------------------
upup
------解决方案--------------------
我知道﹗現在是能加載得了你已經建的XML先呀﹗
這是你之前建的XML
<?xml version= "1.0 " encoding= "UTF-8 "?>
<roles>
<param name= "rolename " value= "123 " />
<param name= "rolename " value= "789 " />
</roles>

這時你加加載不了提示出錯
==================================================
newdom.LoadXml(Server.MapPath(@ "xml\\roleuser.xml "))
根级别上的数据无效。 行 1,位置 1。
====================================================

是因為這里﹕ <?xml version= "1.0 " encoding= "UTF-8 "?>
應改為﹕ <?xml version= "1.0 " encoding= "UTF-16 "?>