直接上程序:
1.以下是XML文档:
<?xml version=”1.0″ encoding=”UTF-8″?>
<contactList id=”0″>
<contact id=”001″ class=”style”>
<name>张三</name>
<age>20</age>
<phone>134222223333</phone>
<email>
[email protected]</email>
[email protected]</email>
<qq>432221111</qq>
</contact>
<contact id=”002″>
<name>李四</name>
<age>20</age>
<phone>134222225555</phone>
<email>
[email protected]</email>
[email protected]</email>
<qq>432222222</qq>
</contact>
<contactTwo>
<name>王五</name>
<age>32</age>
<phone>465431341</phone>
<emali>
[email protected]</emali>
[email protected]</emali>
<qq>46164694</qq>
</contactTwo>
<test>测试</test>
<test>其他用途</test>
</contactList>
2.以下是java测试程序:
2.以下是java测试程序:
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
/**
* 使用dom4j操作xml
* 对xml属性操作
*
*/
public class Test{
@Test
public void test() throws Exception{
//读取XML文件,获得document对象
SAXReader reader = new SAXReader();
Document document = reader.read(new File(“./src/contact.xml”));
//获得某个节点的属性对象
Element rootElem = document.getRootElement();
//获取根节点属性对象
Attribute rootAttr = rootElem.attribute(“id”);
//获取指定节点属性对象
Element contactElem = rootElem.element(“contact”);
Attribute contactAttr = contactElem.attribute(“id”);
//遍历某个节点的所有属性
for (Iterator it = contactElem.attributeIterator();it.hasNext();){
Attribute conAttr= (Attribute)it.next();
String conTxt = conAttr.getValue();
String conAttrName = conAttr.getName();
System.out.println(conAttrName+” = “+conTxt);
}
//设置某节点的属性和值
contactElem.addAttribute(“name”, “zhangsan”);
//设置(更改)某属性的值
Attribute nameAttr = contactElem.attribute(“name”);
nameAttr.setValue(“lisi”);
//删除某节点的指定属性
contactElem.remove(nameAttr);
//将某节点的属性和值写入xml文档中
XMLWriter writer = new XMLWriter(new FileWriter(“./src/contact.xml”));
writer.write(document);
writer.close();
/**
* 如果文档中有中文需要设置字符编码
* 用如下语句:
* OutputFormat format = OutputFormat.createPrettyPrint();
* format.setEncoding(“GBK”);
* XMLWriter writer = new XMLWriter(new FileWriter(“./src/contact.xml”),format);
*/
//获取指定对象的属性名
System.out.println(rootAttr.getName());
System.out.println(contactAttr.getName());
//获取指定对象的属性值
System.out.println(contactAttr.getValue());
System.out.println(rootAttr.getValue());
}
}
转载请注明来源网站:blog.ytso.com谢谢!
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/14778.html