`
zhangzcz1999
  • 浏览: 144398 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

(转)Word文档解析介绍(using Jacob & HtmlParser)

阅读更多
Java中Word的解析方法据我了解有多种,如通过jacob调用office com组件处理Word文档对象,这里介绍的方法是结合jacob与HtmlParser解析word文档内容,希望对利用该方法解析word的网友有帮助。

1. word转换为html
    这里使用Jacob实现word到html的转换。Jacob的使用这里就不详述了,不过前提条件是服务器端需要安装微软的Office(当然操作系统也需要是微软家的)。word转换为html功能写在工具类Word2Html中(类似的做法网络上有很多介绍),这样针对word的解析转换为对html的解析。



2. 解析html(using HtmlParser)
    在介绍html解析前,有必要说明一下word文档的内容结构。

    对一份有标题编号的word文档来说,从首页至尾页以编号为依据可以看作是一棵深度遍历树,相邻编号之间是父子或兄弟关系,编号所在的层次通过标题格式定 义。另外,文档中可以认为是结构化的内容包括:各种约定格式的标题、表格、约定格式的段落、项目符号 和 编号。转换为html后,利用HtmlParser可以方便地解析这些结构化的数据。如果解析出来的数据要求保持父子关系的引用,则需要记录解析对象在html文档中的位置,HtmlParser有提供这些功能。

    在HtmlParser API中,识别节点主要通过标签名称构造过滤器(NodeFilter)得到NodeList,在处理NodeList中的Node,关于HtmlParser介绍可以参考 http://htmlparser.sourceforge.net/

    下面介绍应用HtmlParser解析html常用元素的一些通用方法,这些方法封装在抽象类AbstractHtmlParser中,下面针对一些常用方法进行说明(详见附件):

    1. 获取一个节点下所有的text

protected String getAllTextInNode(Node node) {
		StringBuffer sb = new StringBuffer();
		if (node instanceof TextNode) {
			TextNode textNode = (TextNode) node;
			String text = textNode.getText().trim();
			if (!StringUtil.isEmpty(text)) {
				sb.append(text.replace(" ", " ").replace(">", ">")
						.replace("&lt;", "<").replace("&quot;", "\"").replace(
								"&amp;", "&").replace("&apos;", "'"));
			}
		} else if (node instanceof RemarkNode) {
			// do nothing
		} else if (node instanceof TagNode) {
			TagNode tagNode = (TagNode) node;
			NodeList nl = tagNode.getChildren();
			if (null != nl) {
				for (SimpleNodeIterator i = nl.elements(); i.hasMoreNodes();) {
					sb.append(getAllTextInNode(i.nextNode()));
				}
			}
		}
		return sb.toString();
	}
 

    2. 解析带有表头的表格,返回List<Map<String, String>>

编码编码名称描述
18k
216k
332k
4


/**
	 * 以表第一行(带有thead元素)作为表头,后续行为List,首行作为List中Map的key,后续行每列作为该Map的value。<br>
	 * 后续行如果列数与表头不匹配,将终止处理。
	 * <p>
	 * @param table
	 * @return
	 */
	protected List<Map<String, String>> getListFromTheadTable(Node table) {
		List<Map<String, String>> result = new ArrayList<Map<String,String>>();
		TagNameFilter theadFilter = new TagNameFilter(TAG_THEAD);
		NodeList theadList = table.getChildren().extractAllNodesThatMatch(
				theadFilter);
		TagNode theadNode = null;
		if (theadList != null && theadList.size() > 0) {
			theadNode = (TagNode)theadList.elementAt(0);
		}
		if (theadNode == null) {
			return result;
		}
		
		// process rows following <thead>
		HasSiblingFilter theadSibFilter = new HasSiblingFilter(theadFilter);
		AndFilter andFilter = new AndFilter(new TagNameFilter(TAG_TR), theadSibFilter);
		NodeList trNodeList = table.getChildren().extractAllNodesThatMatch(new TagNameFilter(TAG_TR));
		String[] keys = getTdTextInRow(trNodeList.elementAt(0));
		for (int i=1; i<trNodeList.size(); i++) {
			Map<String, String> map = new HashMap<String, String>();
			String [] values = getTdTextInRow(trNodeList.elementAt(i));
			if (values.length != keys.length) {
				break; // 后续行如果列数与表头不匹配,将终止处理后续行
			}
			for (int k=0; k<keys.length; k++) {
				map.put(keys[k], values[k]);
			}
			result.add(map);
		}

		return result;
	}


    3. 解析获取形如下Table的数据对,返回Map<String, String> :

编号 0001 名称 卡状态
编码长度 2 发布序号 01
说明



/**
	 * @param table
	 * @return
	 */
	protected Map<String, String> getMapFormTable(Node table) {
		Map<String, String> result = new HashMap<String, String>();
		NodeList trNodeList = table.getChildren();
		for (SimpleNodeIterator trIter = trNodeList.elements(); trIter
				.hasMoreNodes();) {
			Node trNode = trIter.nextNode();
			if (!isNodeType(trNode, TAG_TR)) {
				continue;
			}
			NodeList tdNodeList = trNode.getChildren();
			Node tdKeyNode = tdNodeList.elementAt(0);
			Node tdValNode = null;
			while (true) {
				if (!isNodeType(tdKeyNode, TAG_TD)) {
					tdKeyNode = getNextSiblingNode(tdKeyNode, TAG_TD);
					continue;
				}
				tdValNode = getNextSiblingNode(tdKeyNode, TAG_TD);
				if (null == tdValNode) {
					break;
				}
				result.put(getAllTextInNode(tdKeyNode),
						getAllTextInNode(tdValNode));

				tdKeyNode = getNextSiblingNode(tdValNode, TAG_TD);
				if (null == tdKeyNode) {
					break;
				}
			}
		}
		return result;
	}
   


    4. 获取一行中td标记包含的text,返回String[]
/**
	 * 获取一行中td标记包含的text,返回String[]
	 * 
	 * @param trNode
	 * @return
	 */
	protected String[] getTdTextInRow(Node trNode) {
		if (!isNodeType(trNode, TAG_TR)) {
			return null;
		}
		List<String> values = new ArrayList<String>();
		NodeList tdNodeList = trNode.getChildren().extractAllNodesThatMatch(
				new TagNameFilter(TAG_TD));
		for (SimpleNodeIterator it = tdNodeList.elements(); it.hasMoreNodes();) {
			values.add(getAllTextInNode(it.nextNode()));
		}
		return values.toArray(new String[] {});
	}
 
    5. 在指定父节点下查找指定TagName的子孙节点,按照深度遍历返回第一个TagName的子孙节点

/**
	 * 在指定父节点下查找指定TagName的子孙节点,按照深度遍历返回第一个TagName的子孙节点
	 * 
	 * @param parent
	 * @param tagName
	 * @return
	 */
	protected Node getNodeInChildren (Node parent, String tagName) {
		if (parent == null) {
			return null;
		}
		NodeList children = parent.getChildren();
		if (children == null) {
			return null;
		}
		for (SimpleNodeIterator it=children.elements(); it.hasMoreNodes(); ) {
			Node child = it.nextNode();
			if (child instanceof TagNode) {
				if (tagName.equalsIgnoreCase(((TagNode) child).getTagName())) {
					return child;
				} else {
					return getNodeInChildren(child, tagName);
				}
			}
		}
		return null;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics