.net+Jquery 对XML的操作

后台XML操作

下面分别记录了2种对XML文档的操作类以及方法和属性。其实这2种操作原理都是一样,区别在于一个是.net原由的XmlDocument类和与 其对应的相关类、方法属性等,另一个则是最新的.net3.5中才有的XDocument类和与其对应的相关类、方法属性等。

需要加的二个命名空间是

using System.IO;
using System.Web;

 

公共部分代码很少,如下:


  ///   <summary>
        
///  xml文件名称
        
///   </summary>
         private   static   string  xmlName  =   " liuwei.xml " ;
        
///   <summary>
        
///  返回XML文档的物理路径
        
///   </summary>
        
///   <returns></returns>
         public   static   string  XmlPath()
        {
            
return  System.Web.HttpContext.Current.Server.MapPath(xmlName);
        }

        
///   <summary>
        
///  创建Xml文件
        
///   </summary>
        
///   <returns></returns>
         public   static   int  CreateXml()
        {
            
if (File.Exists(XmlPath())) // XML文件存在
                 return   9 ;
            
try
            {
                FileStream fs 
=  File.Create(XmlPath());
                
// 这里定义content变量是为了在发布时代码不错为!
                 string  content  =   " <?xml version=/ " 1.0 / "  encoding=/ " utf - 8 / " ?><Root></Root> " ;
                
byte [] info  =   new  UTF8Encoding( true ).GetBytes(content );
                fs.Write(info, 
0 , info.Length);
                fs.Close();
                
return   6 ;
            }
            
catch  (Exception ex)
            {
                
return   4 ;
            }
            
        }

 

接着就是具体对XML文档操作的代码,如下:

(1)、 XDocument类、XElement 类、XAttribute

上面3个类的必须添加System.Xml.Linq命名空间才能使用。

下面是把更、删、改写在一个方法里,如果需要可以单独针对每个操作写对应的方法。 


///   <summary>
        
///  对XML结点的增、删、改
        
///   </summary>
        
///   <returns></returns>
         public   static   bool  CreateNode( string  option)
        {
            
// 定义一个当前请就对象,方便获取POST传入的参数
            HttpRequest hr  =  HttpContext.Current.Request;
            
string  id = ( "" + hr[ " id " ]);
            
try
            {
                
// 加载已经存在的XML文档并创建XDocuemnt对象
                XDocument doc  =  XDocument.Load(XmlPath());
                
if  (option  ==   " Insert " )
                {
                    
// 获得所有参数
                     string  name  =  ( ""   +  hr[ " name " ]);
                    
string  age  =  ( ""   +  hr[ " age " ]);
                    
string  sex  =  ( ""   +  hr[ " sex " ]);
                    
string  city  =  ( ""   +  hr[ " city " ]);
                    
string  hometown  =  ( ""   +  hr[ " hometown " ]);
                    
string  orderby  =  ( ""   +  hr[ " orderby " ]);
                    
// 创建结点的属性id,date,orderby,并为其赋值
                    XElement xmlEle1  =   new  XElement( " Xml_Linq " ,
                                                    
new  XAttribute( " id " , System.Guid.NewGuid()),
                                                    
new  XAttribute( " date " , DateTime.Now.ToString()),
                                                    
new  XAttribute( " orderby " , orderby));

                    
// 下面5个Add是为结点添加子结点
                    xmlEle1.Add( new  XElement( " name " , name));
                    xmlEle1.Add(
new  XElement( " age " , age));
                    xmlEle1.Add(
new  XElement( " sex " , sex));
                    xmlEle1.Add(
new  XElement( " city " , city));
                    xmlEle1.Add(
new  XElement( " hometown " , hometown));

                    
// 把创建好的一个带有属性和子结点的结点添加到XML文档的根结点Root下面,并保 存。
                    doc.Root.Add(xmlEle1);
                    doc.Save(XmlPath());
                    
return   true ;
                }
                
else   if  (option  ==   " Update " )
                {
                    
string  name_U  =  ( ""   +  hr[ " name_U " ]);
                    
string  age_U  =  ( ""   +  hr[ " age_U " ]);
                    
string  sex_U  =  ( ""   +  hr[ " sex_U " ]);
                    
string  city_U  =  ( ""   +  hr[ " city_U " ]);
                    
string  hometown_U  =  ( ""   +  hr[ " hometown_U " ]);
                    
string  orderby_U  =  ( ""   +  hr[ " orderby_U " ]);

                    
// 得到XDocument对象根结点下所有
                    var xml  =  doc.Root.Elements( " Xml_Linq " );
                    
foreach  (XElement xe  in  xml) // 循环操作所有Xml_Linq子结点。
                    {
                        
// 通过Xml_Linq结点的id属性来判断操作的正确结点
                         if  (xe.Attribute( " id " ).Value  ==  id)
                        {
                            xe.SetAttributeValue(
" orderby " , orderby_U); // 操作 Xml_Linq结点的orderby属性
                            xe.SetElementValue( " name " , name_U); // 操作Xml_Linq结点的 name子结点
                            xe.SetElementValue( " age " , age_U); // 操作Xml_Linq结点的age 子结点
                            xe.SetElementValue( " sex " , sex_U); // 操作Xml_Linq结点的sex 子结点
                            xe.SetElementValue( " city " , city_U); // 操作Xml_Linq结点的 city子结点
                            
// 操作Xml_Linq结点的hometown子结点
                            xe.SetElementValue( " hometown " , hometown_U);
                            
break ;
                        }
                    }
                    doc.Save(XmlPath());
                    
return   true ;
                }
                
else   if  (option  ==   " Del " )
                {
                    
string  ids  =  ( ""   +  hr[ " ids " ]);
                    
if  ( string .IsNullOrEmpty(ids))
                        
return   false ;

                    
string [] arr  =  ids.Split( ' , ' );
                    
for  (var i  =   0 ; i  <  arr.Length  -   1 ; i ++ )
                    {
                        
// 通过LINQ查出所有需要删除的Xml_Linq子结点
                        var xml  =  from x  in  doc.Root.Elements( " Xml_Linq " )
                                  
where  x.Attribute( " id " ).Value  ==  arr[i]
                                  select x;
                        
// 删除子结点
                        xml.Remove();
                    }
                    doc.Save(XmlPath());
                    
return   true ;
                }
                
return   false ;
            }
            
catch  (Exception er)
            {
                er.ToString();
                
return   false ;
            }   
        }

  以上的就是用Linq来对XML操作的代码。

 

(2)、XmlDocument类、XmlElement类、XmlAttribute类

上面的3个类需要引用System.Xml命名空间。

 (这块代码晚上回去在贴上来)

 

前台操作。

前台的显示有好多办法,而我则用JQUERY中的AJAX来显示。这样显示比较麻烦,因为在实际显示中,碰到了兼容问题。IE6和Firefox对 XML文挡的节点找寻不能统一,只能分别显示。代码有点多,以后可能会发现更精简的显示办法。

 


<% @ Page Language = " C# "  AutoEventWireup = " true "   CodeFile = " Default.aspx.cs "  Inherits = " _Default "   %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml" >
< head  runat ="server" >
    
< title > 无标题页 </ title >
    
< script  src ="jquery.js"  type ="text/javascript" ></ script >
    
< script  type ="text/javascript" >
// 排序用的对象
var  XmlNodeList = function (lwid,date,orderby,name,age,sex,city,hometown){
        
this .lwid = lwid;
        
this .date = date;
        
this .orderby = orderby;
        
this .name = name;
        
this .age = age;
        
this .sex = sex;
        
this .city = city;
        
this .hometown = hometown;
}; 
// 把内容存放在数组里再排序
var  arrlist = new  Array();
// 读数据
     function  ShowXml()
    {
       
var  aid = "" ;
       
var  date = "" ;
       
var  orderby = "" ;
       
var  name = "" ;
       
var  age = "" ;
       
var  sex = "" ;
       
var  city = "" ;
       
var  hometown = "" ;
$.ajax({
            type:
" GET " ,
            url:
" liuwei.xml " ,
            dataType:
" xml " ,
            data:
"" ,
            cache:
false ,
            success:
function (data)
            {
                
var  html = "" ;
                
var  len = data.documentElement.childNodes.length;
                
// 这里的IF[判断XML文档是否有数 据
                 if (len  ==   0   ||  (len == 1   &&
                   data.documentElement.childNodes[
0 ].nodeName  ==   " #text " ))
                {
                    html
+= " <ul><li> 无任何内容</li></ul> " ;
                }
                
else
                {
                    
for ( var  i = 0 ;i < data.documentElement.childNodes.length;i ++ )
                    {
                         
// 因为火狐在分析XML文档时总把子结 点与子结点之间添加了一个
                          // "/n   "结点,不知道这是为什 么,所以必须要下面的判断
                          if (data.documentElement.childNodes[i].childNodes.length > 0 )
                         {   
                             
// 这里的index1--index5 的值是针对IE6时结点的索引。
                              // 每个 Root根结点下面的Xml_Linq子结点下面的子结点只有5个。
                              var  index1 = 0 ;
                             
var  index2 = 1 ;
                             
var  index3 = 2 ;
                             
var  index4 = 3 ;
                             
var  index5 = 4 ;
                             
if (isFirefox = navigator.userAgent.indexOf( " Firefox " ) > 0 )
                             {
                                
// 上面说过为什么要区分 FireFox,所以这里
                                 // 就必须 是相隔一位的索引,不然就会报错
                                index1 = 1 ;
                                index2
= 3 ;
                                index3
= 5 ;
                                index4
= 7 ;
                                index5
= 9 ;
                             }           
  aid
= data.documentElement.childNodes[i].attributes.getNamedItem( " id " ).nodeValue;
 date
= data.documentElement.childNodes[i].attributes.getNamedItem( " date " ).nodeValue;
 orderby
= parseInt(data.documentElement.childNodes[i].attributes.getNamedItem( " orderby " ).nodeValue);                            
       name
= data.documentElement.childNodes[i].childNodes[index1].firstChild.nodeValue;
      age
= data.documentElement.childNodes[i].childNodes[index2].firstChild.nodeValue;
       sex
= data.documentElement.childNodes[i].childNodes[index3].firstChild.nodeValue;
       city
= data.documentElement.childNodes[i].childNodes[index4].firstChild.nodeValue;
       hometown
= data.documentElement.childNodes[i].childNodes[index5].firstChild.nodeValue;
                             
                             
// 把数据放在数组里,这样下面就可以对 这些数据排序
                             arrlist[i]  =   new  XmlNodeList(aid,date,orderby,name,age,sex,city,hometown);
                         }   
                    }
                    
// 排序内容
                    arrlist.sort( function (tObj,sObj){ return  sObj.orderby - tObj.orderby}); 
                     
for ( var  j = 0 ;j < arrlist.length;j ++ )
                     {    
                         
// 这里是对火狐的区分,如果不加火狐就 会出现错误
                          if (arrlist[j]  !=  undefined)
                         {  
                                
var  id = arrlist[j].lwid.toString();
 html
+= " <ul id='lw_ " +  id  + " '><li>id:<span id='id_ " +  id  + " '> " ;
 html
+= " <a href='javascript:void(0)' onclick=Update(' " +  id  + " ')> " +  id  + " </a></span></li> " ;
 html
+= " <li>date:<span id='date_ " +  id  + " '> " +  arrlist[j].date.toString()  + " </span></li> "
 html
+= " <li>name:<span id='name_ " +  id  + " '> " +  arrlist[j].name.toString()  + " </span></li> "
html
+= " <li>age:<span id='age_ " +  id  + " '> " +  arrlist[j].age.toString()  + " </span></li> "
html
+= " <li>sex:<span id='sex_ " +  id  + " '> " +  arrlist[j].sex.toString()  + " </span></li> "
html
+= " <li>city:<span id='city_ " +  id  + " '> " +  arrlist[j].city.toString()  + " </span></li> "
html
+= " <li>hometown:<span id='hometown_ " +  id  + " '> " +  arrlist[j].hometown.toString()  + " </span></li> " ;
html
+= " <li>orderby:<span id='orderby_ " +  id  + " '> " +  arrlist[j].orderby.toString()  + " </span></li> " ;
html
+= " <li><input type='checkbox' id='cb_ " +  id  + " ' name='cb' onclick=Del(this);></li></ul> " ;    
                         }
                     }
                 }
                $(
" #show_xml " ).html(html);
            },
            error:
function (a,b,c){
                alert(c);
            } 
        });
     }
    
</ script >
</ head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div  id ="showresult" ></ div >
    
< div >
        
< asp:Button  ID ="btnCreateXml"  runat ="server"  Text ="创建XML"  OnClick ="btnCreateXml_Click"   />
    
</ div >
    
< input  type ="hidden"  name ="option"  id ="option"  value =""   />
    
< input  type ="hidden"  id ="id"  name ="id"  value =""   />
    
< div  id ="Insert" >
        
<!--
        这里与上面一样
-->
         
< p > name: < input  type ="text"  name ="name"  id ="name"  value =""   /></ p >
        
< p > age: < input  type ="text"  name ="age"  id ="age"  value =""   /></ p >
        
< p > sex: < input  type ="text"  name ="sex"  id ="sex"  value =""   /></ p >
        
< p > city: < input  type ="text"  name ="city"  id ="city"  value =""   /></ p >
        
< p > hometown: < input  type ="text"  name ="hometown"  id ="hometown"  value =""   /></ p >
        
< p > orderby: < input  type ="text"  name ="orderby"  id ="orderby"  value =""   /></ p >
        
        
< div >< asp:Button  ID ="btnCreateNode"  runat ="server"  Text ="创建 XmlNode"  OnClick ="btnCreateNode_Click"   /></ div >
    
</ div >
    
< div   id ="Update"  style ="display:none;" >
         
< p > name: < input  type ="text"  name ="name_U"  id ="name_U"  value =""   /></ p >
        
< p > age: < input  type ="text"  name ="age_U"  id ="age_U"  value =""   /></ p >
        
< p > sex: < input  type ="text"  name ="sex_U"  id ="sex_U"  value =""   /></ p >
        
< p > city: < input  type ="text"  name ="city_U"  id ="city_U"  value =""   /></ p >
        
< p > hometown: < input  type ="text"  name ="hometown_U"  id ="hometown_U"  value =""   /></ p >
        
< p > orderby: < input  type ="text"  name ="orderby_U"  id ="orderby_U"  value =""   /></ p >
        
< div >< asp:Button  ID ="btnUpdate"  runat ="server"  Text ="更新"  OnClick ="btnUpdate_Click"   /></ div >
    
</ div >
    
< div  id ="show_xml" ></ div >
    
< input  type ="hidden"  name ="ids"  id ="ids"  value =""   />
    
< asp:Button  ID ="btnDel"  runat ="server"  Text ="删除所选项"  OnClick ="btnDel_Click" />
    
</ form >
    
< script  type ="text/javascript" >
        ShowXml();
        
function  Update(id)
        {
            $(
" #id " ).val(id);
            $(
" #date_U " ).val($( " #date_ " + id).html());
            $(
" #name_U " ).val($( " #name_ " + id).html());
            $(
" #age_U " ).val($( " #age_ " + id).html());
            $(
" #sex_U " ).val($( " #sex_ " + id).html());
            $(
" #city_U " ).val($( " #city_ " + id).html());
            $(
" #hometown_U " ).val($( " #hometown_ " + id).html());
            $(
" #orderby_U " ).val($( " #orderby_ " + id).html());
            $(
" #Insert " ).hide();
            $(
" #Update " ).show();
            location.href
= " #Update " ;
        }
        
var  ids = "" ;
        
function  Del(obj)
        {
            
if (obj.checked  ==   true )
            {
                ids
+= obj.id.replace( " cb_ " , "" ) + " , " ;
            }
            
else
            {
                ids
= ids.replace(obj.id.replace( " cb_ " , "" ) + " , " , "" );
            }
            $(
" #ids " ).val(ids);
        }
    
</ script >
</ body >
</ html >

你可能感兴趣的:(jquery,.net,xml,文档,firefox,LINQ)