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

.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;
    }

java使用dom4j和XPath解析XML与.net 操作XML小结的更多相关文章

  1. 简单用DOM4J结合XPATH解析XML

    由于DOM4J在解析XML时只能一层一层解析,所以当XML文件层数过多时使用会很不方便,结合XPATH就可以直接获取到某个元素 使用dom4j支持xpath的操作的几种主要形式    第一种形式   ...

  2. Dom4J配合XPath解析schema约束的xml配置文件问题

    如果一个xml文件没有引入约束,或者引入的是DTD约束时,那么使用dom4j和xpath是可以正常解析的,不引入约束的情况本文不再展示. 引入DTD约束的情况 mybook.dtd: <?xml ...

  3. Java之dom4j的简单解析和生成xml的应用

    一.dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的.dom4j是一个十分优秀的JavaXML API,具有性能优异.功能强大和极其易使用的特点,它的性能超过sun公 ...

  4. python 使用xpath解析含有命名空间(xmlns)的xml

    解决办法: from lxml import etree xml = etree.parse("./cee.xml") root = xml.getroot() print(roo ...

  5. [XML] C# XmlHelper操作Xml文档的帮助类 (转载)

    点击下载 XmlHelper.rar 主要功能如下所示 /// <summary> /// 类说明:XmlHelper /// 编 码 人:苏飞 /// 联系方式:361983679 // ...

  6. 使用Dom4j的xPath解析xml文件------xpath语法

    官方语法地址:http//www.w3school.com.cn/xpath/index.asp xpath使用路径表达式来选取xml文档中的节点或节点集.节点是通过沿着路径(path)或者步(ste ...

  7. Java 创建xml文件和操作xml数据

    java中的代码 import java.io.File; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; ...

  8. [XML] C#XMLProcess操作Xml文档的帮助类 (转载)

    点击下载 XMLProcess.rar 主要功能如下所示 看下面代码吧 /// <summary> /// 类说明:XMLProcess /// 编 码 人:苏飞 /// 联系方式:361 ...

  9. JAVA通过XPath解析XML性能比较(原创)

    (转载请标明原文地址) 最近在做一个小项目,使用到XML文件解析技术,通过对该技术的了解和使用,总结了以下内容. 1 XML文件解析的4种方法 通常解析XML文件有四种经典的方法.基本的解析方式有两种 ...

随机推荐

  1. 网页title标题的闪动效果

    通过网页title来提示用户有新消息这个功能很常见,比如现在的微博,还有一些邮箱,这个功能都很常见. 显示信息数: <input type="text" id="t ...

  2. 递归:这帮坑爹的小兔崽子 - 零基础入门学习Python023

    递归:这帮坑爹的小兔崽子 让编程改变世界 Change the world by program 斐波那契数列的递归实现 这节课我们用斐波那契(Fibonacci)数列的递归实现来作为第一个例子吧,斐 ...

  3. hdu 2807 The Shortest Path

    http://acm.hdu.edu.cn/showproblem.php?pid=2807 第一次做矩阵乘法,没有优化超时,看了别人的优化的矩阵乘法,就过了. #include <cstdio ...

  4. VCMI Mods list

    http://heroescommunity.com/viewthread.php3?TID=40902 http://heroes3wog.net/ http://heroes3towns.com/ ...

  5. CentOS下安装无线网卡驱动 (转)

    1. 确定自己的网卡和内核版本:lspci | grep Network  #根据输出的信息确定网卡的型号.uname -a             #确定内核版本 2. 配置yum使用RPMForg ...

  6. 独立写作(A or B)

    开头:On contemporary society(一般的背景)/ With the advent of the technologically advanced society (the info ...

  7. 【CF689D Friends and Subsequences】二分搜索,区间查询

    题意:给定两个整数序列a,b,将a,b对齐,问有多少个区间满足a的区间内最大值等于b的区间内最小值. 数据范围:区间长度n属于[1, 200000],序列中的元素在整型范围内 思路:枚举所有n*(n+ ...

  8. gitlab升级方法

    gitlab升级方法:国内网络环境推荐方法二方法一:官网的升级方式 (1)停止git服务 gitlab-ctl stop unicorn gitlab-ctl stop sidekiq gitlab- ...

  9. [Regular Expressions] Match the Start and End of a Line

    We can use: ^: match the beginning $: match the end Let's say we have the string like the following: ...

  10. OSX: 私人定制Dock默认程序图标

    不论什么一个新用户第一次登陆后,OSX都会自己主动地在用户的Dock中列出系统默认的应用程序图标,这些图标随着OSX版本号的不同而不同. 系统管理员有的时候须要改变这些系统默认图标,或者加入自己的或者 ...