学java要学xml吗_XML学习-Java学习记录

c4a22e3588fc?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

XML.png

使用xpath解析xml文档!!

import org.dom4j.*;

import org.dom4j.io.SAXReader;

import org.junit.Before;

import org.junit.Test;

import java.io.InputStream;

import java.util.List;

/**

使用JUnit进行单元测试

*/

public class DemoXPath {

private Document document; //声明一个文档对象

/**

在每个测试方法前执行

*/

@Before

public void init() throws DocumentException {

InputStream inputStream = DemoXPath.class.getResourceAsStream("/Contact.xml");

document = new SAXReader().read(inputStream);

}

/**

每个测试方法可以直接使用document对象

绝对路径

*/

@Test

public void testAbsolutePath() {

String xpath = "/contactList/contact/name";

//得到第一个name元素,父元素转成子元素

Element node = (Element) document.selectSingleNode(xpath);

System.out.println(node.getText());

//得到多个元素

List nodes = document.selectNodes(xpath);

for (Node node1 : nodes) {

Element element = (Element) node1;

System.out.println(element.getText());

}

}

/**

相对路径

*/

@Test

public void testRelativePath() {

//得到contactList元素

Node node = document.selectSingleNode("/contactList");

//得到子元素,注:node也有这两个方法, . 表示当前路径

Element element = (Element) node.selectSingleNode("./contact/name");

System.out.println(element.getText());

}

/**

全文搜索

*/

@Test

public void testGlobalSearch() {

List nodes = document.selectNodes("//email");

for (Node node : nodes) {

Element element = (Element) node;

System.out.println(element.getText());

}

}

/**

属性查找

*/

@Test

public void testAttributeFind() {

//得到的属性集合

/*List nodes = document.selectNodes("//@id");

for (Node node : nodes) {

Attribute attribute = (Attribute) node;

System.out.println("属性名:" + attribute.getName() + ",属性值:" + attribute.getValue());

}*/

//得到包含属性id的contact元素

/*List nodeList = document.selectNodes("//contact[@id]");

for (Node node : nodeList) {

Element element = (Element) node;

System.out.println(element);

}*/

//得到属性id=3的元素

Node node = document.selectSingleNode("//contact[@id=3]");

System.out.println(node);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值