我最近在做xml文件比较的功能,需要得到差异元素所在的行号。
jdom中有元素行号的信息。具体做法是:
1.修改SAXHandler, 将其实现的借口和方法全部去掉,只留下DefaultHandler的方法。
我们只需要关注setDocumentLocator(org.xml.sax.Locator locator) ;和startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException 这2个方法。其中第一个方法中的locator中包含了行号信息。
2.修改Element,原始的Element中不包含行号属性,需要新建一个类ElementWithLineNumber承Element.
public class ElementWithLineNumber extends Element {
private int lineNumber;
}
3. 修改第一步中提到的第二个方法。以jdom2.0.5为例,将:
final Element element = currentLocator == null ? factory.element(localName, namespace) : factory.element(currentLocator.getLineNumber(), currentLocator.getColumnNumber(), localName, namespace);
修改为:
final Element element = new ElementWithLineNumber(localName, namespace);
((ElementWithLineNumber)element).setLineNumber(currentLocator.getLineNumber());
4.调用:
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SAXHandler hand = new SAXHandler();
sp.parse(
new File(
"c:\\workspace\\eclipse\\TestXmlCompare\\xmlCompareConfig.xml"),
hand);
Document doc = hand.getDocument();
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for (int i = 0; i < allChildren.size(); i++) {
Element a = (Element) allChildren.get(i);
System.out.print(a.getName() + ":" + a.getText() + " row="
+ ((ElementWithLineNumber) a).getLineNumber() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
希望可以帮到你。