XML文件:

<?xml version="1.0" encoding="UTF-8"?>

<vrvscript>
<item ID="1021" isSelf="n"/>
<item ID="1023" isSelf="n"/>
<item ID="1003" isSelf="n"/>
<item ID="1020" isSelf="n"/>
<item ID="1022" isSelf="n"/>
</vrvscript>

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

// 获取XML
Document document = XMLUtil.getDocument(xmlPath);
Element root = document.getRootElement(); Iterator<?> ruleNodes = root.elementIterator("item");
while (ruleNodes.hasNext()) {
Element ruleElement = (Element) ruleNodes.next();
// 修改isSelf的属性值
Attribute isSelfAttr = ruleElement.attribute("isSelf");
isSelfAttr.setValue("n");
}
writeXml(document, xmlPath.getPath());
    /**
* 输出xml文件
*
* @param document
* @param filePath
* @throws IOException
*/
public static void writeXml(Document document, String filePath) throws IOException {
File xmlFile = new File(filePath);
XMLWriter writer = null;
try {
if (xmlFile.exists())
xmlFile.delete();
writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
writer.close();
}
}

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

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

给XML元素增加属性

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

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

package com.vrv.paw.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map; import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; /**
* 操作XML文件的工具类
*
* @author glw
*/
public class XMLUtil {
/**
* 得到XML文档
*
* @param xmlFile
* 文件名(路径)
* @return XML文档对象
* @throws DocumentException
*/
public static Document getDocument(String xmlFile) {
SAXReader reader = new SAXReader();
reader.setEncoding("UTF-8");
File file = new File(xmlFile);
try {
if (!file.exists()) {
return null;
} else {
return reader.read(file);
}
} catch (DocumentException e) {
throw new RuntimeException(e + "->指定文件【" + xmlFile + "】读取错误");
}
} /**
* 得到XML文档(编码格式-gb2312)
*
* @param xmlFile
* 文件名(路径)
* @return XML文档对象
* @throws DocumentException
*/
public static Document getDocument_gb2312(String xmlFile) {
SAXReader reader = new SAXReader();
reader.setEncoding("gb2312");
File file = new File(xmlFile);
try {
if (!file.exists()) {
return null;
} else {
return reader.read(file);
}
} catch (DocumentException e) {
throw new RuntimeException(e + "->指定文件【" + xmlFile + "】读取错误");
}
} public static String getText(Element element) {
try {
return element.getTextTrim();
} catch (Exception e) {
throw new RuntimeException(e + "->指定【" + element.getName() + "】节点读取错误");
} } /**
* 增加xml文件节点
*
* @param document
* xml文档
* @param elementName
* 要增加的元素名称
* @param attributeNames
* 要增加的元素属性
* @param attributeValues
* 要增加的元素属性值
*/
public static Document addElementByName(Document document, String elementName, Map<String, String> attrs, String cdata) {
try {
Element root = document.getRootElement();
Element subElement = root.addElement(elementName);
for (Map.Entry<String, String> attr : attrs.entrySet()) {
subElement.addAttribute(attr.getKey(), attr.getValue());
}
subElement.addCDATA(cdata);
} catch (Exception e) {
throw new RuntimeException(e + "->指定的【" + elementName + "】节点增加出现错误");
}
return document;
} /**
* 删除xml文件节点
*/
@SuppressWarnings("unchecked")
public static Document deleteElementByName(Document document, String elementName) {
Element root = document.getRootElement();
Iterator<Object> iterator = root.elementIterator("file");
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
// 根据属性名获取属性值
Attribute attribute = element.attribute("name");
if (attribute.getValue().equals(elementName)) {
root.remove(element);
document.setRootElement(root);
break;
}
}
return document;
} /**
* 输出xml文件
*
* @param document
* @param filePath
* @throws IOException
*/
public static void writeXml(Document document, String filePath) throws IOException {
File xmlFile = new File(filePath);
XMLWriter writer = null;
try {
if (xmlFile.exists())
xmlFile.delete();
writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
writer.close();
}
} /**
* 创建Document及根节点
*
* @param rootName
* @param attributeName
* @param attributeVaule
* @return
*/
public static Document createDocument(String rootName, String attributeName, String attributeVaule) {
Document document = null;
try {
document = DocumentHelper.createDocument();
Element root = document.addElement(rootName);
root.addAttribute(attributeName, attributeVaule);
} catch (Exception e) {
throw new RuntimeException(e + "->创建的【" + rootName + "】根节点出现错误");
}
return document;
} /**
* 删除xml文件节点
*/
@SuppressWarnings("unchecked")
public static Document deleteElementAddressByName(Document document, String elementName) {
Element root = document.getRootElement();
Iterator<Object> iterator = root.elementIterator("address");
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
// 根据属性名获取属性值
Attribute attribute = element.attribute("name");
if (attribute.getValue().equals(elementName)) {
root.remove(element);
document.setRootElement(root);
break;
}
}
return document;
} /**
* 删除属性等于某个值的元素
* @param document XML文档
* @param xpath xpath路径表达式
* @param attrName 属性名
* @param attrValue 属性值
* @return
*/
@SuppressWarnings("unchecked")
public static Document deleteElementByAttribute(Document document, String xpath, String attrName, String attrValue) {
Iterator<Object> iterator = document.selectNodes(xpath).iterator();
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
Element parentElement = element.getParent();
// 根据属性名获取属性值
Attribute attribute = element.attribute(attrName);
if (attribute.getValue().equals(attrValue)) {
parentElement.remove(element);
}
}
return document;
}
}

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. C# WPF打印报表

    前天我的一个同学由于打印报表而苦恼,所以就介绍了一下WPF的打印报表,希望能帮助到大家. 展示报表 1. 首先新建项“报表”,选定项目,右击,点击“添加”->“新建项”->“报表”

  2. Ubuntu 查看文件以及磁盘空间大小命令df

    (1)查看文件大小 查看当前文件夹下所有文件大小(包括子文件夹)    du -sh   # du -h 15M     ./package 16K     ./.fontconfig 4.0K    ...

  3. 1257: [CQOI2007]余数之和sum - BZOJ

    Description 给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值,其中k mod i表示k除以i的余数.例如j(5, ...

  4. 【POJ】【3071】Football

    概率DP kuangbin总结中的第10题 简单的画个比赛图,会发现是一颗完全二叉树,且同一层的子树之间各自独立,只有在合并得到更高一层结果时才结合. 所以我们可以按比赛轮数进行DP,f[i][j]表 ...

  5. 【Vijos】【1923】漫长的等待

    可持久化线段树 这次是询问一段区间内权值 在给定范围内的点的数量,同样是可持久化线段树简单操作…… //Vijos 1923 #include<vector> #include<cs ...

  6. [bzoj 3031] 理科男

    题意 给定一个进制分数 求是否是循环小数,且求出循环节长度 题解 暴力 il int find(int p){ int head=last[p%mod]; while(head&&pr ...

  7. asp.net-(含:模拟登陆,照片列表)

    一.画好用户登录界面 同时换下请求的地址. 获取用户信息及判断代码插入位置: 一.画好用户登录界面 同时换下请求的地址. 获取用户信息及判断代码插入位置: <%@ WebHandler Lang ...

  8. 深入浅出Java并发包—原子类操作

    我们知道,JDK1.5以后引入了并发包(java.util.concurrent)用于解决多CPU时代的并发问题,而并发包中的类大部分是基于Queue的并发类,Queue在大多数情况下使用了原子类(A ...

  9. 解决virtualbox 虚拟机不能ping通win7

    凭经验猜测是由于防火墙引起的,关闭防火墙再ping,果然可行.google说这是由于“win7 防火墙默认的禁ping策略”引起的.但是关闭防火墙很不安全,可以按照以下步骤为防火墙添加入站规则来解决问 ...

  10. Project Euler 76:Counting summations

    题目链接 原题: It is possible to write five as a sum in exactly six different ways: 4 + 13 + 23 + 1 + 12 + ...