xml解析最常用的方法

本文介绍如何使用Java进行XML文档的操作,包括创建、查询、修改及删除等常见任务,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String xpath = String format("/root/shools/shool[@id=\"%d\"]",xx);
String xpath = "/root/shools";
String xpath = "/root/shools/shool[@id=1]";
String xpath = "//root/shools/shool/class/student[@name=\"alice\"]";

1.获得文档
a.新的
Document document = DocumentHelper.createDocument();
b.旧的
InputStreamReader read=new InputStreamReader(new FileInputStream(filePath), “UTF8”);
SAXReader reader = new SAXReader();
Document document = reader.read(read);

2.查找document单个节点
Node node = document.selectSingleNode(xpath);

3.查找document子节点列表
List<Node> list = document.selectNodes(xpath);

4.写文档
OutputFormat format = null;
format = OutputFormat.createCompactFormat(); 紧凑格式
format = OutputFormat.createPrettyPrint(); 非紧凑格式
format.setTrimText(false); ??
format.setPadText(false); ??
format.setEncoding("GB2312");//用于支持中文
XMLWriter writer = new XMLWriter(new FileWriter(savePath), format);
writer.write( document );
writer.close();

<也能支持中文>
OutputFormat format = OutputFormat.createPrettyPrint(); 非紧凑格式
FileOutputStream fos = new FileOutputStream(savePath);
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.close();


5. 增加根节点
Element root = document.addElement(“root”);

6.新增加元素
Element shoolElement = root.addElement("school");

7.增加属性
shoolElement.addAttribute("shoolName", "xxxx学校");

7.设置元素文本???
element.setText("sdfsdfs");

9.查找node下的单个节点
xpath = String.format("/root/shools/shool/class[@classid=\"%d\"]",1);
Node selNode = node.selectSingleNode(xpath);

10.查找node下的多个节点
List<Node> list = node.selectNodes(xpath);

11. 取得节点属性值
String attribute = node.valueOf("@属性名"); 必加@

12.取得Element属性值
element.attributeValue(attribute_name);

13. 修改属性值
Attribute attribute = element.attribute(attribute_name);
if (attribute != null)
attribute.setValue(attribute_value);

14.删除节点
if (node.getParent() == null)
document.remove(node);
else node.getParent().remove(node);

15.判断字符串是否是合法的XML
DocumentHelper.parseText(content);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值