获取XML节点完整方法

package com.huawei.cddevops;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;


public class test {
 private Map<String ,String> reportMap = new HashMap<String, String>();
 private Node node;
 
 public Map<String, String> getReportMap() {
  return reportMap;
 }

 public void setReportMap(Map<String, String> reportMap) {
  this.reportMap = reportMap;
 }

 public Node getNode() {
  return node;
 }

 public void setNode(Node node) {
  this.node = node;
 }
 public static void main(String[] args) throws FileNotFoundException, DocumentException{
  test t=new test();
  t.xml("d://test.xml");
 }
 public void xml(String filePath) throws FileNotFoundException, DocumentException{
  //判断重复时候不加载
  SAXReader reader = new SAXReader();
  InputStream inputStream = null;
  File file = new File(filePath);
  inputStream = new FileInputStream(file);
   Document document = reader.read(inputStream);
   List<Node> layerNodes = document.selectNodes("//layer");//获取xml根节点
   if(layerNodes.size() > 0 ){
    Node layerNode = layerNodes.get(0);//获取xml名为layer下面的一个节点
     this.setNode(layerNode);
     if(layerNode.selectSingleNode("./book")!=null){
      System.out.println(this.getTextByNodeXpath(this.getNode(), "./book/textbook/@English"));//输出6

      this.getTextByNodeXpath(this.getNode(), "./book/textbook/@Chinese");
      this.getTextByNodeXpath(this.getNode(), "./book/textbook/@mathematics");
    }
   }
 }
 /**
  * 根据Xpath表达式获取节点
  * @param node
  * @param xpath
  * @return
  */
 public static String getTextByNodeXpath(Node node,String xpath){
  Node singNode =  node.selectSingleNode(xpath);//获取节点
  if(singNode==null) return null;
  return singNode.getText();
 }
 public static JSON getJSONFromXml(String xmlString) { 
      XMLSerializer xmlSerializer = new XMLSerializer(); 
      JSON json = xmlSerializer.read(xmlString); 
      return json; 
  }
}

 

以下是名为test.xml文件的内容

<?xml version="1.0" encoding="UTF-8"?>

<cruisecontrol>
  <layer name="test1">
        <book>
          <textbook English="6" Chinese="7" mathematics="9" />
        </book>
    </layer>
</cruisecontrol>

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值