重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Java中的xml文件怎么利用正则表达式进行解析-创新互联

这篇文章将为大家详细讲解有关Java中的xml文件怎么利用正则表达式进行解析,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

临海ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

一、编写Node类

Node对象是文档解析的基础,最终可以通过对象的不同属性实现对文档信息的访问。

Node.java:

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Node implements Serializable {
  // 可以对Node对象持久化保存
  private static final long serialVersionUID = 1L;
  private int id;
  // 节点类型
  private String title;
  // 节点内容
  private String text;
  // 节点属性集合
  private Map attributes = new HashMap();
  // 子节点集合
  private List childNodes = new LinkedList();
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }
  public Map getAttribute() {
    return attributes;
  }
  public void setAttribute(Map attribute) {
    this.attributes = attribute;
  }
  public String getText() {
    return text;
  }
  public void setText(String text) {
    this.text = text;
  }
  public List getChildNode() {
    return childNodes;
  }
  public void setChildNode(List childNode) {
    this.childNodes = childNode;
  }
  // 将属性集合转换成一条完整的字符串
  private String attrToString() {
    if (attributes.isEmpty()) {
      return "";
    }
    Iterator> its = attributes.entrySet().iterator();
    StringBuffer buff = new StringBuffer();
    while (its.hasNext()) {
      Entry entry = its.next();
      buff.append(entry.getKey() + "=\"" + entry.getValue() + "\" ");
    }
    return " " + buff.toString().trim();
  }
  // 输出完整的节点字符串也用到了递归
  @Override
  public String toString() {
    String attr = attrToString();
    if (childNodes.isEmpty() && text == null) {
      return "<" + title + attr + "/>\n";
    } else if (childNodes.isEmpty() && text != null) {
      return "<" + title + attr + ">\n" + text + "\n" + "\n";
    } else {
      StringBuffer buff = new StringBuffer();
      buff.append("<" + title + attr + ">\n");
      if (!text.isEmpty()) {
        buff.append(text + "\n");
      }
      for (Node n : childNodes) {
        buff.append(n.toString());
      }
      buff.append("\n");
      return buff.toString();
    }
  }
}

当前文章:Java中的xml文件怎么利用正则表达式进行解析-创新互联
文章位置:http://cqcxhl.cn/article/ccphsi.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP