使用Jdom2获取XML元素的行号

关键类:

org.jdom2.contrib.input.LineNumberElement

org.jdom2.contrib.input.LineNumberSAXHandler

注意:这两个类在Jdom2-2.0.5.jar中是不存在的,需要下载Jdom2-2.0.5的src包,

下载链接:http://www.java2s.com/Code/Jar/j/Downloadjdom2205sourcesjar.htm

示例Java代码:

 


import java.io.IOException;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.contrib.input.LineNumberElement;
import org.jdom2.contrib.input.LineNumberSAXHandler;
import org.jdom2.filter.Filter;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.jdom2.xpath.jaxen.JaxenXPathFactory;
/**
 * 查找mybatis的配置文件中的所有select元素的行号
 * 
 * @author kent.yang
 *
 */
public class FindElementLineOfXML{
	/**
	 * 查找mybatis的配置文件中的所有select元素的行号
	 * 
	 * @param filePath
	 * @return  
	 */
	public void createDom(String filePath) {
		SAXBuilder saxBuilder = new SAXBuilder();
		saxBuilder.setSAXHandlerFactory(LineNumberSAXHandler.SAXFACTORY);
		Document document = null;
		try {
			document = saxBuilder.build(filePath);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		if (!"mapper".equals(root.getName())) {
			return;
		}
		XPathFactory factory = JaxenXPathFactory.instance();
		Filter filter = Filters.element();
		XPathBuilder builder = new XPathBuilder("//select", filter);
		XPathExpression objs = builder.compileWith(factory);
		List objList = objs.diagnose(root, false).getResult();
		for (Element elm : objList) {
            //解析完成以后其实已经是LineNumberElement,但XPath不支持,所以先用Xpath取Element,再强转
			LineNumberElement lineElm = (LineNumberElement) elm;
			System.out.println("元素:" + elm.getName() + "的行号:" + lineElm.getStartLine());
			
		}
	}

    public static void main(String[] args){
        FindElementLineOfXML fel = new FindElementLineOfXML();
        fel.createDom("D:/CityMapper.xml");
    }

}

XML文件:




	
		
		
		
		
	

	

	
		id, province_id, city_name, description
	

	


运行结果:

元素:select的行号:17

你可能感兴趣的:(使用Jdom2获取XML元素的行号)