首頁>Club>
8
回覆列表
  • 1 # 使用者3558515502465

    我最近在做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<Element> 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(); }希望可以幫到你。

  • 中秋節和大豐收的關聯?
  • 柴犬哪裡買靠譜,推薦一下靠譜柴犬犬舍?