zoukankan      html  css  js  c++  java
  • java使用dom4j和XPath解析XML与.net 操作XML小结

    最近研究java的dom4j包,使用 dom4j包来操作了xml 文件

    包括三个文件:studentInfo.xml(待解析的xml文件), Dom4jReadExmple.java(解析的主要类), TestDom4jReadExmple.java(测试解析的结果) 

    studentInfo.xml

    <?xml version="1.0" encoding="gb2312"?>
    <students>
        <student age="25"><!--如果没有age属性,默认的为20-->
            <name>崔卫兵</name>
            <college>PC学院</college>
            <telephone>62354666</telephone>
            <notes>男,1982年生,硕士,现就读于北京邮电大学</notes>
        </student>

          <student>
            <name>cwb</name>
            <college leader="学院领导">PC学院</college><!--如果没有leader属性,默认的为leader-->
            <telephone>62358888</telephone>
            <notes>男,1987年生,硕士,现就读于中国农业大学</notes>
        </student>
        <student age="45">
            <name>xxxxx</name>
            <college leader="">xxx学院</college>
            <telephone>66666666</telephone>
            <notes>注视中,注释中</notes>
        </student>
        <student age="">
            <name>lxx</name>
            <college>yyyy学院</college>
            <telephone>88888888</telephone>
            <notes>注视中111,注释中222</notes>
        </student>
    </students>

    Dom4jReadExmple.java

    package dom4jExample.read;

    import java.io.File;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;

    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    /**
     * 利用dom4j与XPath进行XML编程
     * @author cuiweibing
     * @since 2007.8.10
     */
    public class Dom4jReadExmple {
     /**
      * 利用XPath操作XML文件,获取指定节点或者属性的值,并放入HashMap中
      * @param filename String 待操作的XML文件(相对路径或者绝对路径)
      * @param hm       HashMap 存放选择的结果,格式:<nodename,nodevalue>或者<nodename+attrname,attrvalue>
      */
     public void getSelectedNodeValue(String filename,HashMap<String,String> hm){
      try {
       SAXReader saxReader = new SAXReader();
       Document document = saxReader.read(new File(filename));
       //获取学生姓名为"崔卫兵"的年龄
       List list = document.selectNodes("/students/student[name="崔卫兵"]/@age");
       Iterator iter = list.iterator();
       if (iter.hasNext()) {
        Attribute attribute = (Attribute) iter.next();
        hm.put("崔卫兵-"+attribute.getName(), attribute.getValue());
       }else{
        hm.put("崔卫兵-age", "20");
       }

       //获取学生姓名为"崔卫兵"的年龄
       list = document.selectNodes("/students/student[name="cwb"]/@age");
       iter = list.iterator();
       if (iter.hasNext()) {
        Attribute attribute = (Attribute) iter.next();
        hm.put("cwb-"+attribute.getName(), attribute.getValue());
       }else{
        hm.put("cwb-age", "20");
       }

          //获取学生姓名为"cwb"所在的学院名称
       list = document.selectNodes("/students/student[name="cwb"]/college");
       iter = list.iterator();
       if (iter.hasNext()) {
         Element element = (Element) iter.next();
         String name = element.getName();
         String value = element.getText();
         hm.put("cwb-"+name, value);
       }

       //获取学生姓名为"cwb"所在学院的领导
       list = document.selectNodes("/students/student[name="cwb"]/college/@leader");
       iter = list.iterator();
       if (iter.hasNext()) {
        Attribute attribute = (Attribute) iter.next();
        hm.put("cwb-college-"+attribute.getName(), attribute.getValue());
       }else{
        hm.put("cwb-college-leader", "leader");
       }

       //获取学生姓名为"lxx"所在的学院名称
       list = document.selectNodes("/students/student[name="lxx"]/college");
       iter = list.iterator();
       if (iter.hasNext()) {
         Element element = (Element) iter.next();
         String name = element.getName();
         String value = element.getText();
         hm.put("lxx-"+name, value);
       }

       //获取学生姓名为"lxx"所在学院的领导
       list = document.selectNodes("/students/student[name="lxx"]/college/@leader");
       iter = list.iterator();
       if (iter.hasNext()) {
        Attribute attribute = (Attribute) iter.next();
        hm.put("lxx-college-"+attribute.getName(), attribute.getValue());
       }else{
        hm.put("lxx-college-leader", "leader");
       }
      } catch (Exception ex) {
       ex.printStackTrace();
      }
     }
    }

    TestDom4jReadExmple.java

    package dom4jExample.read;

    import java.util.HashMap;

    /**
     * 测试Dom4jReadExmple解析的情况
     * @author cuiweibing
     * @since 2007.8.10
     */
    public class TestDom4jReadExmple {
     public static void main(String[] args) {
         try{
           //获取解析完后的解析信息
           HashMap<String,String> hashMap;
           Dom4jReadExmple drb=new Dom4jReadExmple();
           //利用XPath操作XML文件,获取想要的属性值
           hashMap = new HashMap<String,String>();
           drb.getSelectedNodeValue("studentInfo.xml", hashMap);
           System.out.println("崔卫兵-age:"+hashMap.get("崔卫兵-age"));
           System.out.println("cwb-age:"+hashMap.get("cwb-age"));
           System.out.println("cwb-college:"+hashMap.get("cwb-college"));
           System.out.println("cwb-college-leader:"+hashMap.get("cwb-college-leader"));
           System.out.println("lxx-college:"+hashMap.get("lxx-college"));
           System.out.println("lxx-college-leader:"+hashMap.get("lxx-college-leader"));
         }catch(Exception ex){
           ex.printStackTrace();
         }
       }
    }

     运行结果

    崔卫兵-age:25
    cwbage:20
    cwb-college:PC学院
    cwb-college-leader:学院领导
    lxx-college:yyyy学院
    lxx-college-leader:leader 

     弄个综合的例子:

    1. package com.jim.beans;  
    2.   
    3. import java.io.File;  
    4. import java.io.FileNotFoundException;  
    5. import java.io.FileOutputStream;  
    6. import java.io.FileWriter;  
    7. import java.io.IOException;  
    8. import java.io.OutputStreamWriter;  
    9. import java.io.UnsupportedEncodingException;  
    10. import java.util.ArrayList;  
    11. import java.util.Iterator;  
    12. import java.util.List;  
    13.   
    14. import org.dom4j.Attribute;  
    15. import org.dom4j.Document;  
    16. import org.dom4j.DocumentException;  
    17. import org.dom4j.DocumentHelper;  
    18. import org.dom4j.Element;  
    19. import org.dom4j.io.SAXReader;  
    20. import org.dom4j.io.XMLWriter;  
    21.   
    22. public class DepartmentBean {  
    23.       
    24.     private String ID;   //主键,没有任何意义  
    25.     private String bh;   //部门编号  
    26.     private String name; //部门名称  
    27.     private String tel;  //部门电话  
    28.     private String address;  //部门地址  
    29.       
    30.     private File file;   //要读取的 xml文件  
    31.       
    32.       
    33.     public DepartmentBean() {  
    34.           
    35.     }  
    36.       
    37.     public DepartmentBean(File file) {  
    38.         this.file = file;  
    39.     }  
    40.       
    41.     public DepartmentBean(String id, String bh, String name, String tel, String address) {  
    42.           
    43.         ID = id;  
    44.         this.bh = bh;  
    45.         this.name = name;  
    46.         this.tel = tel;  
    47.         this.address = address;  
    48.     }  
    49.       
    50.     public String getAddress() {  
    51.         return address;  
    52.     }  
    53.   
    54.     public void setAddress(String address) {  
    55.         this.address = address;  
    56.     }  
    57.   
    58.     public String getBh() {  
    59.         return bh;  
    60.     }  
    61.   
    62.     public void setBh(String bh) {  
    63.         this.bh = bh;  
    64.     }  
    65.   
    66.     public String getID() {  
    67.         return ID;  
    68.     }  
    69.   
    70.     public void setID(String id) {  
    71.         ID = id;  
    72.     }  
    73.   
    74.     public String getName() {  
    75.         return name;  
    76.     }  
    77.   
    78.     public void setName(String name) {  
    79.         this.name = name;  
    80.     }  
    81.   
    82.     public String getTel() {  
    83.         return tel;  
    84.     }  
    85.   
    86.     public void setTel(String tel) {  
    87.         this.tel = tel;  
    88.     }  
    89.       
    90.     //查询若干个部门 支持模糊查询  
    91.     public ArrayList search(String attrName,String attrValue) throws DocumentException {  
    92.           
    93.         ArrayList al = new ArrayList();  
    94.         List list = null;  
    95.         //File f = new File("d:\department.xml"); //把要解析的xml文件包装成File类型  
    96.         SAXReader saxReader = new SAXReader(); //加载XML文档  
    97.         saxReader.setEncoding("UTF-8");  
    98.         Document document = saxReader.read(this.file);  
    99.           
    100.         /* 采用了 dom4j 支持 xPath 这个用法 */  
    101.         if((attrName == null || attrName.trim().equals(""))  
    102.                 ||(attrValue == null || attrValue.trim().equals(""))) {   
    103.             list = document.selectNodes("/departments/department");  
    104.         }else {  
    105.             //[注]: 下面这句采用的是 精确查询 等效于 某个属性=值  
    106.             //list = document.selectNodes("/departments/department[@"+attrName+"='"+attrValue+"']");  
    107.             //[注]: 下面这句采用的是 模糊查询 等效于 某个属性 like %值%  
    108.             list = document.selectNodes("/departments/department[contains(@"+attrName+",'" + attrValue + "')]");  
    109.         }  
    110.           
    111.         Iterator iterator = list.iterator();  
    112.         DepartmentBean departmentBean = null;  
    113.         while(iterator.hasNext()) {  
    114.               
    115.             Element element = (Element)iterator.next();  
    116.             departmentBean = new DepartmentBean();  
    117.             departmentBean.setID(<b style="color:black;background-color:#ffff66">element.attributeValue</b>("id"));  
    118.             departmentBean.setBh(<b style="color:black;background-color:#ffff66">element.attributeValue</b>("bh"));  
    119.             departmentBean.setName(<b style="color:black;background-color:#ffff66">element.attributeValue</b>("name"));  
    120.             departmentBean.setTel(<b style="color:black;background-color:#ffff66">element.attributeValue</b>("tel"));  
    121.             departmentBean.setAddress(<b style="color:black;background-color:#ffff66">element.attributeValue</b>("address"));  
    122.               
    123.             al.add(departmentBean);  
    124.         }  
    125.         return al;  
    126.     }  
    127.     //查询某个部门  
    128.     public DepartmentBean getDepartment(String attrName,String attrValue) throws DocumentException {  
    129.           
    130.         ArrayList al = search(attrName,attrValue);  
    131.         if(al != null && al.size() > 0) {  
    132.             return (DepartmentBean)al.get(0);  
    133.         }else {  
    134.             return null;  
    135.         }  
    136.     }  
    137.       
    138.     //添加部门  
    139.     public void add(DepartmentBean newDepartmentBean)  throws DocumentException, IOException {  
    140.           
    141.           
    142.         Document document = DocumentHelper.createDocument();  
    143.         //创建根节点,并返回要节点  
    144.         Element departmentsElement = document.addElement("departments");  
    145.         departmentsElement.addComment("所有的部门信息");  
    146.           
    147.         //向根节点departments中加入department子节点  
    148.         Element departmentElement =  null;  
    149.           
    150.         departmentElement = departmentsElement.addElement("department");  
    151.         departmentElement.addAttribute("id",newDepartmentBean.getID());  
    152.         departmentElement.addAttribute("bh",newDepartmentBean.getBh());  
    153.         departmentElement.addAttribute("name",newDepartmentBean.getName());  
    154.         departmentElement.addAttribute("tel",newDepartmentBean.getTel());  
    155.         departmentElement.addAttribute("address",newDepartmentBean.getAddress());  
    156.           
    157.           
    158.         //File f = new File("d:\department.xml"); //把要解析的xml文件包装成File类型  
    159.         SAXReader saxReader = new SAXReader(); //加载XML文档  
    160.         saxReader.setEncoding("UTF-8");     
    161.         Document documentRead = saxReader.read(this.file);  
    162.         List list = documentRead.selectNodes("/departments/department");  
    163.         Iterator iterator = list.iterator();  
    164.           
    165.         while(iterator.hasNext()) {  
    166.               
    167.             departmentElement = departmentsElement.addElement("department");  
    168.             Element element = (Element)iterator.next();  
    169.               
    170.             Attribute attrID = element.attribute("id");  
    171.             departmentElement.addAttribute("id",attrID.getValue());  
    172.               
    173.             Attribute attrBh = element.attribute("bh");  
    174.             departmentElement.addAttribute("bh",attrBh.getValue());  
    175.               
    176.             Attribute attrName = element.attribute("name");  
    177.             departmentElement.addAttribute("name",attrName.getValue());  
    178.               
    179.             Attribute attrTel = element.attribute("tel");  
    180.             departmentElement.addAttribute("tel",attrTel.getValue());  
    181.               
    182.             Attribute attrAddress = element.attribute("address");  
    183.             departmentElement.addAttribute("address",attrAddress.getValue());  
    184.         }  
    185.           
    186.         //把修改后document写到原有的department.xml文件,以覆盖原有的department.xml文件  
    187.         XMLWriter output = new XMLWriter(new OutputStreamWriter(new FileOutputStream(this.file),"UTF-8"));  
    188.         output.write(document);  
    189.         output.close();  
    190.           
    191.     }  
    192.       
    193.     //编辑部门  
    194.     public void edit(String attrName,String attrValue,DepartmentBean newDepartmentBean)  throws DocumentException, IOException {  
    195.           
    196.         //File f = new File("d:\department.xml"); //把要解析的xml文件包装成File类型  
    197.         SAXReader saxReader = new SAXReader(); //加载XML文档  
    198.         saxReader.setEncoding("UTF-8");     
    199.         Document document = saxReader.read(this.file);  
    200.         List list = null;  
    201.         Iterator iterator = null;  
    202.         if((attrName == null || attrName.trim().equals(""))  
    203.                 ||(attrValue == null || attrValue.trim().equals(""))) { //如果设置的修改条件为 null ,则什么也不做  
    204.             return ;  
    205.         }else {  
    206.             list = document.selectNodes("/departments/department[@"+attrName+"='"+attrValue+"']");  
    207.         }  
    208.           
    209.         if(list == null || list.size() == 0) { //如果设置的修改条件没有符合的记录,则什么也不做  
    210.             return ;  
    211.         }else {  
    212.             iterator = list.iterator();  
    213.             while(iterator.hasNext()) {  
    214.                   
    215.                 Element e = (Element) iterator.next();  
    216.                 Attribute attrB = e.attribute("bh");  
    217.                 attrB.setValue(newDepartmentBean.getBh());  
    218.                 Attribute attrN = e.attribute("name");  
    219.                 attrN.setValue(newDepartmentBean.getName());  
    220.                 Attribute attrT = e.attribute("tel");  
    221.                 attrT.setValue(newDepartmentBean.getTel());  
    222.                 Attribute attrA = e.attribute("address");  
    223.                 attrA.setValue(newDepartmentBean.getAddress());  
    224.             }  
    225.         }  
    226.           
    227.         //把修改后document写到原有的department.xml文件,以覆盖原有的department.xml文件  
    228.         XMLWriter output = new XMLWriter(new OutputStreamWriter(new FileOutputStream(this.file),"UTF-8"));  
    229.         output.write(document);  
    230.         output.close();  
    231.     }  
    232.       
    233.     //删除部门  
    234.     public void del(String attrName,String attrValue) throws DocumentException, IOException {  
    235.           
    236.         //File f = new File("d:\department.xml"); //把要解析的xml文件包装成File类型  
    237.         SAXReader saxReader = new SAXReader(); //加载XML文档  
    238.         saxReader.setEncoding("UTF-8");     
    239.         Document documentRead = saxReader.read(this.file);  
    240.         Document documentWrite = null;  
    241.         List list = null;  
    242.           
    243.         if((attrName == null || attrName.trim().equals(""))  
    244.                 ||(attrValue == null || attrValue.trim().equals(""))) { //如果设置的修改条件为 null ,则什么也不做  
    245.             return ;  
    246.         }else {  
    247.             list = documentRead.selectNodes("/departments/department[@"+attrName+"!='"+attrValue+"']");  
    248.         }  
    249.           
    250.         documentWrite = DocumentHelper.createDocument();  
    251.         Element departmentsElement = documentWrite.addElement("departments");  
    252.         departmentsElement.addComment("所有的部门信息");  
    253.           
    254.         if(list == null || list.size() == 0) { //如果是全删除了,则什么也不做  
    255.               
    256.             //把修改后document写到原有的department.xml文件,以覆盖原有的department.xml文件  
    257.             XMLWriter output = new XMLWriter(new OutputStreamWriter(new FileOutputStream(this.file),"UTF-8"));  
    258.             output.write(documentWrite);  
    259.             output.close();  
    260.               
    261.             return ;  
    262.         }else {  
    263.             //向根节点departments中加入department子节点  
    264.             Element departmentElement =  null;  
    265.             Iterator iterator = list.iterator();  
    266.               
    267.             while(iterator.hasNext()) {  
    268.                   
    269.                 departmentElement = departmentsElement.addElement("department");  
    270.                   
    271.                 Element element = (Element)iterator.next();  
    272.                   
    273.                 Attribute attrID = element.attribute("id");  
    274.                 departmentElement.addAttribute("id",attrID.getValue());  
    275.                   
    276.                 Attribute attrBh = element.attribute("bh");  
    277.                 departmentElement.addAttribute("bh",attrBh.getValue());  
    278.                   
    279.                 Attribute attrName2 = element.attribute("name");  
    280.                 departmentElement.addAttribute("name",attrName2.getValue());  
    281.                   
    282.                 Attribute attrTel = element.attribute("tel");  
    283.                 departmentElement.addAttribute("tel",attrTel.getValue());  
    284.                   
    285.                 Attribute attrAddress = element.attribute("address");  
    286.                 departmentElement.addAttribute("address",attrAddress.getValue());  
    287.             }  
    288.             //把修改后document写到原有的department.xml文件,以覆盖原有的department.xml文件  
    289.             XMLWriter output = new XMLWriter(new OutputStreamWriter(new FileOutputStream(this.file),"UTF-8"));  
    290.             output.write(documentWrite);  
    291.             output.close();  
    292.         }  
    293.     }  
    294.     //得到 xml 文件中最大的主键值 + 1  
    295.     public int getMaxID() throws DocumentException {  
    296.           
    297.         SAXReader saxReader = new SAXReader(); //加载XML文档  
    298.         saxReader.setEncoding("UTF-8");  
    299.         Document document = saxReader.read(this.file);  
    300.           
    301.         List list = document.selectNodes("/departments/department");  
    302.         Iterator iterator = null;  
    303.         int max = 0;  
    304.           
    305.         if(list == null || list.size() == 0) {  
    306.             max = 0;  
    307.         }else {  
    308.               
    309.             iterator = list.iterator();  
    310.             while(iterator.hasNext()) {  
    311.                   
    312.                 Element element = (Element)iterator.next();  
    313.                 String maxStr = <b style="color:black;background-color:#ffff66">element.attributeValue</b>("id");  
    314.                 int maxInt = Integer.parseInt(maxStr);  
    315.                 if(maxInt > max) {  
    316.                     max = maxInt;  
    317.                 }  
    318.             }  
    319.         }  
    320.         return max + 1;  
    321.     }  
    322.       
    323.     public static void main(String[] args) throws DocumentException, IOException {  
    324.           
    325.         File f = new File("d:\department.xml");  
    326.         DepartmentBean db = new DepartmentBean(f);  
    327.         System.out.println(db.getMaxID());  
    328.         //大家可以在这里写一些调用上面的 search ,add , del , edit 方法代码来测试测试,department.xml 文件在附件中已上传了此外还要要到两个特殊的包一个名叫jaxen-1.1.1.jar,还有一个叫dom4j-1.6.1.jar大家可以自己下载  
    329.     }  
    330. }  

     

    .net 操作XML小结

     一、简单介绍

    using System.Xml;
    //初始化一个xml实例
    XmlDocument xml=new XmlDocument();

    //导入指定xml文件
    xml.Load(path);
    xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));

    //指定一个节点
    XmlNode root=xml.SelectSingleNode("/root");

    //获取节点下所有直接子节点
    XmlNodeList childlist=root.ChildNodes;

    //判断该节点下是否有子节点
    root.HasChildNodes;

    //获取同名同级节点集合
    XmlNodeList nodelist=xml.SelectNodes("/Root/News");

    //生成一个新节点
    XmlElement node=xml.CreateElement("News");

    //将节点加到指定节点下,作为其子节点
    root.AppendChild(node);

    //将节点加到指定节点下某个子节点前
    root.InsertBefore(node,root.ChildeNodes[i]);

    //为指定节点的新建属性并赋值
    node.SetAttribute("id","11111");

    //为指定节点添加子节点
    root.AppendChild(node);

    //获取指定节点的指定属性值
    string id=node.Attributes["id"].Value;

    //获取指定节点中的文本
    string content=node.InnerText;

    //保存XML文件
    string path=Server.MapPath("~/file/bookstore.xml");
    xml.Save(path);
    //or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); 

    二、具体实例

    在C#.net中如何操作XML
    需要添加的命名空间:
    using System.Xml;

    定义几个公共对象:
    XmlDocument xmldoc ;
    XmlNode xmlnode ;
    XmlElement xmlelem ;

    1,创建到服务器同名目录下的xml文件:


    方法一:
    xmldoc = new XmlDocument ( ) ;
    //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
    XmlDeclaration xmldecl;
     xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);
     xmldoc.AppendChild ( xmldecl);

    //加入一个根元素
    xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ;
    xmldoc.AppendChild ( xmlelem ) ;
    //加入另外一个元素
    for(int i=1;i<3;i++)
    {

    XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees> 
    XmlElement xe1=xmldoc.CreateElement("Node");//创建一个<Node>节点 
    xe1.SetAttribute("genre","李赞红");//设置该节点genre属性 
    xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性

    XmlElement xesub1=xmldoc.CreateElement("title"); 
    xesub1.InnerText="CS从入门到精通";//设置文本节点 
    xe1.AppendChild(xesub1);//添加到<Node>节点中 
    XmlElement xesub2=xmldoc.CreateElement("author"); 
    xesub2.InnerText="候捷"; 
    xe1.AppendChild(xesub2); 
    XmlElement xesub3=xmldoc.CreateElement("price"); 
    xesub3.InnerText="58.3"; 
    xe1.AppendChild(xesub3);

    root.AppendChild(xe1);//添加到<Employees>节点中 
    }
    //保存创建好的XML文档
    xmldoc.Save ( Server.MapPath("data.xml") ) ;

    //////////////////////////////////////////////////////////////////////////////////////
    结果:在同名目录下生成了名为data.xml的文件,内容如下,
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
    </Employees>


    方法二:
    XmlTextWriter xmlWriter;
       string strFilename = Server.MapPath("data1.xml") ;

       xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档
       xmlWriter.Formatting = Formatting.Indented;
       xmlWriter.WriteStartDocument();
       xmlWriter.WriteStartElement("Employees");

       xmlWriter.WriteStartElement("Node");
       xmlWriter.WriteAttributeString("genre","李赞红");
       xmlWriter.WriteAttributeString("ISBN","2-3631-4");

       xmlWriter.WriteStartElement("title");
       xmlWriter.WriteString("CS从入门到精通");
       xmlWriter.WriteEndElement();

       xmlWriter.WriteStartElement("author");
       xmlWriter.WriteString("候捷");
       xmlWriter.WriteEndElement();

       xmlWriter.WriteStartElement("price");
       xmlWriter.WriteString("58.3");
       xmlWriter.WriteEndElement();

       xmlWriter.WriteEndElement();

       xmlWriter.Close();
    //////////////////////////////////////////////////////////////////////////////////////
    结果:
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
    </Employees>

    2,添加一个结点:

    XmlDocument xmlDoc=new XmlDocument(); 
    xmlDoc.Load(Server.MapPath("data.xml")); 
    XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees> 
    XmlElement xe1=xmlDoc.CreateElement("Node");//创建一个<Node>节点 
    xe1.SetAttribute("genre","张三");//设置该节点genre属性 
    xe1.SetAttribute("ISBN","1-1111-1");//设置该节点ISBN属性

    XmlElement xesub1=xmlDoc.CreateElement("title"); 
    xesub1.InnerText="C#入门帮助";//设置文本节点 
    xe1.AppendChild(xesub1);//添加到<Node>节点中 
    XmlElement xesub2=xmlDoc.CreateElement("author"); 
    xesub2.InnerText="高手"; 
    xe1.AppendChild(xesub2); 
    XmlElement xesub3=xmlDoc.CreateElement("price"); 
    xesub3.InnerText="158.3"; 
    xe1.AppendChild(xesub3);

    root.AppendChild(xe1);//添加到<Employees>节点中 
    xmlDoc.Save ( Server.MapPath("data.xml") );

    //////////////////////////////////////////////////////////////////////////////////////
    结果:在xml原有的内容里添加了一个结点,内容如下,
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="张三" ISBN="1-1111-1">
        <title>C#入门帮助</title>
        <author>高手</author>
        <price>158.3</price>
      </Node>
    </Employees>

    3,修改结点的值(属性和子结点):

    XmlDocument xmlDoc=new XmlDocument(); 
    xmlDoc.Load( Server.MapPath("data.xml") );

    XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

    foreach(XmlNode xn in nodeList)//遍历所有子节点 

    XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型 
    if(xe.GetAttribute("genre")=="张三")//如果genre属性值为“张三” 

    xe.SetAttribute("genre","update张三");//则修改该属性为“update张三”

    XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点 
    foreach(XmlNode xn1 in nls)//遍历 

    XmlElement xe2=(XmlElement)xn1;//转换类型 
    if(xe2.Name=="author")//如果找到 

    xe2.InnerText="亚胜";//则修改




    xmlDoc.Save( Server.MapPath("data.xml") );//保存。

    //////////////////////////////////////////////////////////////////////////////////////
    结果:将原来的所有结点的信息都修改了,xml的内容如下,
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="update张三" ISBN="1-1111-1">
        <title>C#入门帮助</title>
        <author>亚胜</author>
        <price>158.3</price>
      </Node>
    </Employees>

    4,修改结点(添加结点的属性和添加结点的自结点):
    XmlDocument xmlDoc=new XmlDocument(); 
    xmlDoc.Load( Server.MapPath("data.xml") );

    XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

    foreach(XmlNode xn in nodeList) 

    XmlElement xe=(XmlElement)xn; 
    xe.SetAttribute("test","111111");

    XmlElement xesub=xmlDoc.CreateElement("flag"); 
    xesub.InnerText="1"; 
    xe.AppendChild(xesub); 

    xmlDoc.Save( Server.MapPath("data.xml") );

    //////////////////////////////////////////////////////////////////////////////////////
    结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下,
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4" test="111111">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
        <flag>1</flag>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4" test="111111">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
        <flag>1</flag>
      </Node>
      <Node genre="update张三" ISBN="1-1111-1" test="111111">
        <title>C#入门帮助</title>
        <author>亚胜</author>
        <price>158.3</price>
        <flag>1</flag>
      </Node>
    </Employees>

    5,删除结点中的某一个属性:
    XmlDocument xmlDoc=new XmlDocument(); 
    xmlDoc.Load( Server.MapPath("data.xml") ); 
    XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 
    foreach(XmlNode xn in xnl) 

    XmlElement xe=(XmlElement)xn; 
    xe.RemoveAttribute("genre");//删除genre属性

    XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点 
    foreach(XmlNode xn1 in nls)//遍历 

    XmlElement xe2=(XmlElement)xn1;//转换类型 
    if(xe2.Name=="flag")//如果找到 

    xe.RemoveChild(xe2);//则删除



    xmlDoc.Save( Server.MapPath("data.xml") );

    //////////////////////////////////////////////////////////////////////////////////////]
    结果:删除了结点的一个属性和结点的一个子结点,内容如下,
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node ISBN="2-3631-4" test="111111">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node ISBN="2-3631-4" test="111111">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node ISBN="1-1111-1" test="111111">
        <title>C#入门帮助</title>
        <author>亚胜</author>
        <price>158.3</price>
      </Node>
    </Employees>

    6,删除结点:
    XmlDocument xmlDoc=new XmlDocument(); 
    xmlDoc.Load( Server.MapPath("data.xml") ); 
    XmlNode root=xmlDoc.SelectSingleNode("Employees");
    XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 
    for(int i=0;i<xnl.Count;i++)
    {
    XmlElement xe=(XmlElement)xnl.Item(i); 
    if(xe.GetAttribute("genre")=="张三") 

    root.RemoveChild(xe);
    if(i<xnl.Count)i=i-1;

    }
    xmlDoc.Save( Server.MapPath("data.xml") );

    //////////////////////////////////////////////////////////////////////////////////////]
    结果:删除了符合条件的所有结点,原来的内容:

    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="张三" ISBN="1-1111-1">
        <title>C#入门帮助</title>
        <author>高手</author>
        <price>158.3</price>
      </Node>
      <Node genre="张三" ISBN="1-1111-1">
        <title>C#入门帮助</title>
        <author>高手</author>
        <price>158.3</price>
      </Node>
    </Employees>

    删除后的内容:
    <?xml version="1.0" encoding="gb2312"?>
    <Employees>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
      <Node genre="李赞红" ISBN="2-3631-4">
        <title>CS从入门到精通</title>
        <author>候捷</author>
        <price>58.3</price>
      </Node>
    </Employees>

     7,按照文本文件读取xml

    System.IO.StreamReader myFile =new 
    System.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default);
    //注意System.Text.Encoding.Default

    string myString = myFile.ReadToEnd();//myString是读出的字符串
    myFile.Close();

    三、高级应用 

    /*读取xml数据   两种xml方式*/
    <aaa>
         <bb>something</bb>
         <cc>something</cc>
    </aaa>
     
    <aaa>
        <add key="123" value="321"/>
    </aaa>

    /*第一种方法*/
    DS.ReadXml("your xmlfile name");
    Container.DataItem("bb");
    Container.DataItem("cc");
    DS.ReadXmlSchema("your xmlfile name");
     
    /*第二种方法*/
    <aaa>
        <add key="123" value="321"/>
    </aaa>
    如果我要找到123然后取到321应该怎么写呢?
     
    using System.XML;
    XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument();
    xmlDoc.Load(@"c:Config.xml");
    XmlElement elem = xmlDoc.GetElementById("add");
    string str = elem.Attributes["value"].Value
     
     
    /*第三种方法:  SelectSingleNode  读取两种格式的xml *---/
    --------------------------------------------------------------------
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <appSettings>
           <ConnectionString>Data Source=yf; user id=ctm_dbo;password=123</ConnectionString>             
      </appSettings>
    </configuration>
    --------------------------------------------------------------------------
    XmlDocument doc = new XmlDocument();
    doc.Load(strXmlName);
     
        XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString");
        if(node!=null)
        {
         string k1=node.Value;    //null
         string k2=node.InnerText;//Data Source=yf; user id=ctm_dbo;password=123
         string k3=node.InnerXml;//Data Source=yf; user id=ctm_dbo;password=123
         node=null;
        }
     
    ********************************************************************
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <appSettings>
           <add key="ConnectionString" value="Data Source=yf; user id=ctm_dbo;password=123" />             
      </appSettings>
    </configuration>
    **--------------------------------------------------------------------**
         XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
        if(node!=null)
        {
         string k=node.Attributes["key"].Value;
         string v=node.Attributes["value"].Value;
         node=null;
        }
    *--------------------------------------------------------------------*
        XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
        if(node!=null)
        {
         XmlNodeReader nr=new XmlNodeReader(node);
         nr.MoveToContent();
        //检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。
         nr.MoveToAttribute("value");
         string s=nr.Value;
         node=null;
        }

  • 相关阅读:
    批处理读取INI文件
    重装操作系统的20条原则
    SATA串口硬盘Windows Vista系统驱动安装实录
    中国国家地理高清晰的PDF书籍系列经典珍藏版
    单一职责原则
    理解boost::bind的实参传递方式
    理解C++ dynamic_cast
    C# vs C++之三:静态构造函数
    TDD可以驱动设计吗?
    依赖注入与对象间关系
  • 原文地址:https://www.cnblogs.com/hy928302776/p/3240410.html
Copyright © 2011-2022 走看看