1.新建类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class readXML {
/**
* @param args
* @throws IOException
* @throws JDOMException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, JDOMException, IOException {
SAXBuilder sb=new SAXBuilder();
Document doc=sb.build(new FileInputStream("d:/test.xml"));
//如果在一般的方法中使用
// Document doc=sb.build(getClass().getClassLoader().getResourceAsStream("d:/test.xml"));
Element root=doc.getRootElement(); //HD
List list=root.getChildren("person"); //child
for(int i=0;i<list.size();i++)
{
Element element=(Element) list.get(i);
System.out.println("人员信息");
String id=element.getAttributeValue("id");
String name=element.getChildText("name");
String email=element.getChildText("email");
System.out.println("ID号:"+id);
System.out.println("姓名:"+name);
System.out.println("邮件地址::"+email);
System.out.println("-------------------------------");
}
Element element1=(Element)list.get(0);//得到第一个Person元素
element1.removeAttribute(element1.getAttribute("id"));//删除id属性
Element el=element1.getChild("name");//得到Person下的name元素
el.setText("wang");//设置name为wang
Element element2=(Element)list.get(1);//得到第二个Person元素
Attribute arr=new Attribute("hot","1");//创建属性实例
element2.setAttribute(arr);//为Person添加属性hot="1"
Element e2=element2.getChild("name");
e2.setText("wang");
Attribute arr1=new Attribute("color","red");//创建属性实例
e2.setAttribute(arr1);//为name元素添加属性color="red"
XMLOutputter xml = new XMLOutputter();
xml.output(doc, new FileOutputStream("d:/cute.xml"));//输出新的xml文件
}
}
运行前test.xml
<?xml version="1.0" encoding="UTF-8"?>
<addressbook>
<person id="1">
<name>王奇鹏</name>
<email>wangqipeng@gmail.com</email>
</person>
<person id="2">
<name>王艳明</name>
<email>wangyanming1980@gmail.com</email>
</person>
<person id="3">
<name>王广庆</name>
<email>wangluohuli@sina.com.cn</email>
</person>
</addressbook>
运行后的cute.xml
<?xml version="1.0" encoding="UTF-8"?>
<addressbook>
<person>
<name>wang</name>
<email>wangqipeng@gmail.com</email>
</person>
<person id="2" hot="1">
<name color="red">wang</name>
<email>wangyanming1980@gmail.com</email>
</person>
<person id="3">
<name>王广庆</name>
<email>wangluohuli@sina.com.cn</email>
</person>
</addressbook>
jdom解析xml
最新推荐文章于 2025-08-14 09:04:35 发布