XML文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <vrvscript>
  4. <item ID="1021" isSelf="n"/>
  5. <item ID="1023" isSelf="n"/>
  6. <item ID="1003" isSelf="n"/>
  7. <item ID="1020" isSelf="n"/>
  8. <item ID="1022" isSelf="n"/>
  9. </vrvscript>

修改属性值:要把每个item元素的“isSelf”属性值修改为“y”

  1. // 获取XML
  2. Document document = XMLUtil.getDocument(xmlPath);
  3. Element root = document.getRootElement();
  4.  
  5. Iterator<?> ruleNodes = root.elementIterator("item");
  6. while (ruleNodes.hasNext()) {
  7. Element ruleElement = (Element) ruleNodes.next();
  8. // 修改isSelf的属性值
  9. Attribute isSelfAttr = ruleElement.attribute("isSelf");
  10. isSelfAttr.setValue("n");
  11. }
  12. writeXml(document, xmlPath.getPath());
  1. /**
  2. * 输出xml文件
  3. *
  4. * @param document
  5. * @param filePath
  6. * @throws IOException
  7. */
  8. public static void writeXml(Document document, String filePath) throws IOException {
  9. File xmlFile = new File(filePath);
  10. XMLWriter writer = null;
  11. try {
  12. if (xmlFile.exists())
  13. xmlFile.delete();
  14. writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
  15. writer.write(document);
  16. writer.close();
  17. } catch (UnsupportedEncodingException e) {
  18. e.printStackTrace();
  19. } catch (FileNotFoundException e) {
  20. e.printStackTrace();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. } finally {
  24. if (writer != null)
  25. writer.close();
  26. }
  27. }

获取属性值:采用Element类的attributeValue方法

  1. String policyName = root.attributeValue("PolicyName");

给XML元素增加属性

  1. Element ruleElement = root.addElement("item");
  2. ruleElement.addAttribute("ID", "1101");
  3. ruleElement.addAttribute("isSelf", "y");

一些提供一个dom4j操作XML的工具类:

  1. package com.vrv.paw.utils;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.UnsupportedEncodingException;
  8. import java.util.Iterator;
  9. import java.util.Map;
  10.  
  11. import org.dom4j.Attribute;
  12. import org.dom4j.Document;
  13. import org.dom4j.DocumentException;
  14. import org.dom4j.DocumentHelper;
  15. import org.dom4j.Element;
  16. import org.dom4j.io.OutputFormat;
  17. import org.dom4j.io.SAXReader;
  18. import org.dom4j.io.XMLWriter;
  19.  
  20. /**
  21. * 操作XML文件的工具类
  22. *
  23. * @author glw
  24. */
  25. public class XMLUtil {
  26. /**
  27. * 得到XML文档
  28. *
  29. * @param xmlFile
  30. * 文件名(路径)
  31. * @return XML文档对象
  32. * @throws DocumentException
  33. */
  34. public static Document getDocument(String xmlFile) {
  35. SAXReader reader = new SAXReader();
  36. reader.setEncoding("UTF-8");
  37. File file = new File(xmlFile);
  38. try {
  39. if (!file.exists()) {
  40. return null;
  41. } else {
  42. return reader.read(file);
  43. }
  44. } catch (DocumentException e) {
  45. throw new RuntimeException(e + "->指定文件【" + xmlFile + "】读取错误");
  46. }
  47. }
  48.  
  49. /**
  50. * 得到XML文档(编码格式-gb2312)
  51. *
  52. * @param xmlFile
  53. * 文件名(路径)
  54. * @return XML文档对象
  55. * @throws DocumentException
  56. */
  57. public static Document getDocument_gb2312(String xmlFile) {
  58. SAXReader reader = new SAXReader();
  59. reader.setEncoding("gb2312");
  60. File file = new File(xmlFile);
  61. try {
  62. if (!file.exists()) {
  63. return null;
  64. } else {
  65. return reader.read(file);
  66. }
  67. } catch (DocumentException e) {
  68. throw new RuntimeException(e + "->指定文件【" + xmlFile + "】读取错误");
  69. }
  70. }
  71.  
  72. public static String getText(Element element) {
  73. try {
  74. return element.getTextTrim();
  75. } catch (Exception e) {
  76. throw new RuntimeException(e + "->指定【" + element.getName() + "】节点读取错误");
  77. }
  78.  
  79. }
  80.  
  81. /**
  82. * 增加xml文件节点
  83. *
  84. * @param document
  85. * xml文档
  86. * @param elementName
  87. * 要增加的元素名称
  88. * @param attributeNames
  89. * 要增加的元素属性
  90. * @param attributeValues
  91. * 要增加的元素属性值
  92. */
  93. public static Document addElementByName(Document document, String elementName, Map<String, String> attrs, String cdata) {
  94. try {
  95. Element root = document.getRootElement();
  96. Element subElement = root.addElement(elementName);
  97. for (Map.Entry<String, String> attr : attrs.entrySet()) {
  98. subElement.addAttribute(attr.getKey(), attr.getValue());
  99. }
  100. subElement.addCDATA(cdata);
  101. } catch (Exception e) {
  102. throw new RuntimeException(e + "->指定的【" + elementName + "】节点增加出现错误");
  103. }
  104. return document;
  105. }
  106.  
  107. /**
  108. * 删除xml文件节点
  109. */
  110. @SuppressWarnings("unchecked")
  111. public static Document deleteElementByName(Document document, String elementName) {
  112. Element root = document.getRootElement();
  113. Iterator<Object> iterator = root.elementIterator("file");
  114. while (iterator.hasNext()) {
  115. Element element = (Element) iterator.next();
  116. // 根据属性名获取属性值
  117. Attribute attribute = element.attribute("name");
  118. if (attribute.getValue().equals(elementName)) {
  119. root.remove(element);
  120. document.setRootElement(root);
  121. break;
  122. }
  123. }
  124. return document;
  125. }
  126.  
  127. /**
  128. * 输出xml文件
  129. *
  130. * @param document
  131. * @param filePath
  132. * @throws IOException
  133. */
  134. public static void writeXml(Document document, String filePath) throws IOException {
  135. File xmlFile = new File(filePath);
  136. XMLWriter writer = null;
  137. try {
  138. if (xmlFile.exists())
  139. xmlFile.delete();
  140. writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
  141. writer.write(document);
  142. writer.close();
  143. } catch (UnsupportedEncodingException e) {
  144. e.printStackTrace();
  145. } catch (FileNotFoundException e) {
  146. e.printStackTrace();
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. } finally {
  150. if (writer != null)
  151. writer.close();
  152. }
  153. }
  154.  
  155. /**
  156. * 创建Document及根节点
  157. *
  158. * @param rootName
  159. * @param attributeName
  160. * @param attributeVaule
  161. * @return
  162. */
  163. public static Document createDocument(String rootName, String attributeName, String attributeVaule) {
  164. Document document = null;
  165. try {
  166. document = DocumentHelper.createDocument();
  167. Element root = document.addElement(rootName);
  168. root.addAttribute(attributeName, attributeVaule);
  169. } catch (Exception e) {
  170. throw new RuntimeException(e + "->创建的【" + rootName + "】根节点出现错误");
  171. }
  172. return document;
  173. }
  174.  
  175. /**
  176. * 删除xml文件节点
  177. */
  178. @SuppressWarnings("unchecked")
  179. public static Document deleteElementAddressByName(Document document, String elementName) {
  180. Element root = document.getRootElement();
  181. Iterator<Object> iterator = root.elementIterator("address");
  182. while (iterator.hasNext()) {
  183. Element element = (Element) iterator.next();
  184. // 根据属性名获取属性值
  185. Attribute attribute = element.attribute("name");
  186. if (attribute.getValue().equals(elementName)) {
  187. root.remove(element);
  188. document.setRootElement(root);
  189. break;
  190. }
  191. }
  192. return document;
  193. }
  194.  
  195. /**
  196. * 删除属性等于某个值的元素
  197. * @param document XML文档
  198. * @param xpath xpath路径表达式
  199. * @param attrName 属性名
  200. * @param attrValue 属性值
  201. * @return
  202. */
  203. @SuppressWarnings("unchecked")
  204. public static Document deleteElementByAttribute(Document document, String xpath, String attrName, String attrValue) {
  205. Iterator<Object> iterator = document.selectNodes(xpath).iterator();
  206. while (iterator.hasNext()) {
  207. Element element = (Element) iterator.next();
  208. Element parentElement = element.getParent();
  209. // 根据属性名获取属性值
  210. Attribute attribute = element.attribute(attrName);
  211. if (attribute.getValue().equals(attrValue)) {
  212. parentElement.remove(element);
  213. }
  214. }
  215. return document;
  216. }
  217. }

dom4j修改,获取,增加xml中某个元素的属性值的更多相关文章

  1. JAVA读取XML文件并解析获取元素、属性值、子元素信息

    JAVA读取XML文件并解析获取元素.属性值.子元素信息 关键字 XML读取  InputStream   DocumentBuilderFactory   Element     Node 前言 最 ...

  2. javaScript获取文档中所有元素节点的个数

    HTML+JS 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  3. Java分享笔记:使用entrySet方法获取Map集合中的元素

    /*--------------------------------- 使用entrySet方法取出Map集合中的元素: ....该方法是将Map集合中key与value的关系存入到了Set集合中,这 ...

  4. 在js中获取页面元素的属性值时,弱类型导致的诡异事件踩坑记录,

    前几天写一个js的时候遇到一个非常诡异的事情,这个问题是这样的,我要获取一个页面的DOM元素的val值,判断这个值是否比某个变量大,这个需求原先数字最大也就是10,现在要改了,可能会更多,这个时候我发 ...

  5. tween.js是一款可生成平滑动画效果的js动画库。tween.js允许你以平滑的方式修改元素的属性值。它可以通过设置生成各种类似CSS3的动画效果。

    简要教程 tween.js是一款可生成平滑动画效果的js动画库.相关的动画库插件还有:snabbt.js 强大的jQuery动画库插件和Tweene-超级强大的jQuery动画代理插件. tween. ...

  6. JQuery中操作元素的属性_对象属性

    我们主要是通过attr去获取元素的属性: 看body内容: <body> <p> 账号:<input type="text" id="una ...

  7. (转载)读取xml中的指定节点的值

            /// <summary>         /// 读取xml中的指定节点的值        /// </summary>         private st ...

  8. 读取xml中的指定节点的值

    /// <summary> /// 读取xml中的指定节点的值 /// </summary> private string ReadXmlNode(string filenam ...

  9. CSS3中transform几个属性值的注意点

    transform(变形)是CSS3中的元素的属性,transform的属性值主要包括旋转rotate.扭曲skew.缩放scale和移动translate以及矩阵变形matrix 基本用法可以参考文 ...

随机推荐

  1. JS实现刷新iframe的方法

    <iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe> ...

  2. ruby 格式化当前日期时间

    ruby 格式化当前日期时间 ruby 用Time类获取当前时间. t = Time.new puts t 可以看到输出的是(我现在运行的时间): Sat Jan 29 10:45:22 +0800 ...

  3. android studio 中设置apk的版本号

    今天在mainfest.xml中设置版本号为2,(代码获取到的版本号无效) android:versionCode="2" android:versionName="2. ...

  4. 2433: [Noi2011]智能车比赛 - BZOJ

    Description 新一届智能车大赛在JL大学开始啦!比赛赛道可以看作是由n个矩形区域拼接而成(如下图所示),每个矩形的边都平行于坐标轴,第i个矩形区域的左下角和右上角坐标分别为(xi,1,yi, ...

  5. IntelliJ IDEA 文件夹重命名--解决重命名后js文件引用找不到路径报404错误

    情景: 说明:ExtJS是我后来的改的名字--原来叫extjs,可是当我把在页面的引用地址改为 src="ExtJS/.."后页面就报404错误,我把它改回之前的extjs就可以( ...

  6. Oracle数据库表的备份和数据表的删除操作

    --Oracle数据库中的表备份: --备份语句:在备份之后就可以将这张表的所有数据源删除了,但是之后有人对这张表的数据进行操作,但是在操作完成之后要记得将数据表恢复 CREATE TABLE DZH ...

  7. Matlab实现二进制矩阵转换为十进制

    一.问题描述 [1 1 1 0 1 0 1 1 0 1 0 0 1 1 0] 每两位3转换为一个十进制数,共5列,那么转换后是ceil(5/3)=2列. [7 1 6 1 1 2] 二.问题分析 1. ...

  8. 本地不安装oracle-client,使用pl/sql developer连接数据库

    一.问题描述 本地未安装oracle-client端,由于机器资源有限,希望通过pl/sql developer进行远程数据库连接.单纯的安装pl/sql developer无法远程连接数据库. 二. ...

  9. 在线最优化求解(Online Optimization)之二:截断梯度法(TG)

    在线最优化求解(Online Optimization)之二:截断梯度法(TG) 在预备篇中我们做了一些热身,并且介绍了L1正则化在Online模式下也不能产生较好的稀疏性,而稀疏性对于高维特征向量以 ...

  10. Introduction To Monte Carlo Methods

    Introduction To Monte Carlo Methods I’m going to keep this tutorial light on math, because the goal ...