xml问题之解

package com.suning.ebuy.vgs.airticket.globalImpl;

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.xiao.demo.utils.XmlUtils;


public class XmlTest02 {


public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, Exception {
// TODO Auto-generated method stub
String xml = "<Prices><Price><PsgType>ADT</PsgType></Price><Price><PsgType>CHD</PsgType></Price></Prices>";
Document doc = XmlUtils.getW3CDom(xml);
NodeList nodeList = XmlUtils.runXpath(doc, "//Prices/Price", null);
for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);
getPrices(node,i+1);

}


}


public static void getPrices(Node node,int i) {
String pricesXml = XmlUtils.nodeAsString(node);
System.err.println(pricesXml);
String psgType = XmlUtils.getValueByXpath(node, "//Price["+i+"]/PsgType");
System.err.println("乘客类型:" + psgType);

}

}

两篇文章里面的测试类你对比下就会发现不同之处了,这里我说下自己的理解吧,昨晚睡觉之时,

突然就想到了,如果说两次结果都是和第一次的一样,那么根据对xpath的理解,

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。
这样的结果产生只有一种可能,就是第一次传入的node肯定还是存在的,那么我们就可以根据类似于数组一样的操作

来获得第二个node的想要的标签。于是上面的代码就证明了我的想法。而原来的//Price/PsgType得到的肯定是第一次

的那个node的乘客类型的属性。希望能让自己在以后的开发上多借鉴走过的路。也会觉得如果可以给别人带来代码的

分享也是一种快乐。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值