Javaはxpathとdom4jを使用してxmlを解析します
1 XML文件解析的4种方法
通常解析XML文件有四种经典的方法。基本的解析方式有两种,一种叫SAX,另一种叫DOM。SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。在此基础上,为了减少DOM、SAX的编码量,出现了JDOM,其优点是,20-80原则(帕累托法则),极大减少了代码量。通常情况下JDOM使用时满足要实现的功能简单,如解析、创建等要求。但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。另外一种是DOM4J,是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。具体四种方法的使用,百度一下,会有众多详细的介绍。
2 XPath简单介绍
XPath是一门在XML文档中查找信息的语言。XPath用于在 XML 文档中通过元素和属性进行导航,并对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 同时被构建于 XPath 表达之上。因此,对 XPath 的理解是很多高级 XML 应用的基础。XPath非常类似对数据库操作的SQL语言,或者说JQuery,它可以方便开发者抓起文档中需要的东西。其中DOM4J也支持XPath的使用。
3 DOM4J使用XPath
DOM4J使用XPath解析XML文档是,首先需要在项目中引用两个JAR包:
dom4j-1.6.1.jar:DOM4J软件包,下载地址http://sourceforge.net/projects/dom4j/;
jaxen-xx.xx.jar:通常不添加此包,会引发异常(java.lang.NoClassDefFoundError: org/jaxen/JaxenException),下载地址http://www.jaxen.org/releases.html。
3.1 命名空间(namespace)的干扰
在处理由excel文件或其他格式文件转换的xml文件时,通常会遇到通过XPath解析得不到结果的情况。这种情况通常是由于命名空间的存在导致的。以下述内容的XML文件为例,通过XPath=" // Workbook/ Worksheet / Table / Row[1]/ Cell[1]/Data[1] "进行简单的检索,通常是没有结果出现的。这就是由于命名空间namespace(xmlns="urn:schemas-microsoft-com:office:spreadsheet")导致的。
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <Worksheet ss:Name="Sheet1"> <Table ss:ExpandedColumnCount="81" ss:ExpandedRowCount="687" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="52.5" ss:DefaultRowHeight="15.5625"> <Row ss:AutoFitHeight="0"> <Cell> <Data ss:Type="String">敲代码的耗子</Data> </Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell> <Data ss:Type="String">Sunny</Data> </Cell> </Row> </Table> </Worksheet> </Workbook>
3.2 XPath对带有命名空间的xml文件解析
第一种方法(read1()函数):使用XPath语法中自带的local-name() 和 namespace-uri() 指定你要使用的节点名和命名空间。 XPath表达式书写较为麻烦。
第二种方法(read2()函数):设置XPath的命名空间,利用setNamespaceURIs()函数。
第三种方法(read3()函数):设置DocumentFactory()的命名空间 ,使用的函数是setXPathNamespaceURIs()。二和三两种方法的XPath表达式书写相对简单。
第四种方法(read4()函数):方法和第三种一样,但是XPath表达式不同(程序具体体现),主要是为了检验XPath表达式的不同,主要指完整程度,是否会对检索效率产生影响。
(以上四种方法均通过DOM4J结合XPath对XML文件进行解析)
第五种方法(read5()函数):使用DOM结合XPath对XML文件进行解析,主要是为了检验性能差异。
没有什么能够比代码更能说明问题的了!果断上代码!
packageXPath; importjava.io.IOException; importjava.io.InputStream; importjava.util.HashMap; importjava.util.List; importjava.util.Map; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importjavax.xml.parsers.ParserConfigurationException; importjavax.xml.xpath.XPathConstants; importjavax.xml.xpath.XPathExpression; importjavax.xml.xpath.XPathExpressionException; importjavax.xml.xpath.XPathFactory; importorg.dom4j.Document; importorg.dom4j.DocumentException; importorg.dom4j.Element; importorg.dom4j.XPath; importorg.dom4j.io.SAXReader; importorg.w3c.dom.NodeList; importorg.xml.sax.SAXException; /** *DOM4JDOMXMLXPath */ publicclassTestDom4jXpath{ publicstaticvoidmain(String[]args){ read1(); read2(); read3(); read4();//read3()方法一样,但是XPath表达式不同 read5(); } publicstaticvoidread1(){ /* *uselocal-name()andnamespace-uri()inXPath */ try{ longstartTime=System.currentTimeMillis(); SAXReaderreader=newSAXReader(); InputStreamin=TestDom4jXpath.class.getClassLoader().getResourceAsStream("XPath\\XXX.xml"); Documentdoc=reader.read(in); /*Stringxpath="//*[local-name()='Workbook'andnamespace-uri()='urn:schemas-microsoft-com:office:spreadsheet']" +"/*[local-name()='Worksheet']" +"/*[local-name()='Table']" +"/*[local-name()='Row'][4]" +"/*[local-name()='Cell'][3]" +"/*[local-name()='Data'][1]";*/ Stringxpath="//*[local-name()='Row'][4]/*[local-name()='Cell'][3]/*[local-name()='Data'][1]"; System.err.println("=====uselocal-name()andnamespace-uri()inXPath===="); System.err.println("XPath:"+xpath); @SuppressWarnings("unchecked") List<Element>list=doc.selectNodes(xpath); for(Objecto:list){ Elemente=(Element)o; Stringshow=e.getStringValue(); System.out.println("show="+show); longendTime=System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } }catch(DocumentExceptione){ e.printStackTrace(); } } publicstaticvoidread2(){ /* *setxpathnamespace(setNamespaceURIs) */ try{ longstartTime=System.currentTimeMillis(); Mapmap=newHashMap(); map.put("Workbook","urn:schemas-microsoft-com:office:spreadsheet"); SAXReaderreader=newSAXReader(); InputStreamin=TestDom4jXpath.class.getClassLoader().getResourceAsStream("XPath\\XXX.xml"); Documentdoc=reader.read(in); Stringxpath="//Workbook:Row[4]/Workbook:Cell[3]/Workbook:Data[1]"; System.err.println("=====usesetNamespaceURIs()tosetxpathnamespace===="); System.err.println("XPath:"+xpath); XPathx=doc.createXPath(xpath); x.setNamespaceURIs(map); @SuppressWarnings("unchecked") List<Element>list=x.selectNodes(doc); for(Objecto:list){ Elemente=(Element)o; Stringshow=e.getStringValue(); System.out.println("show="+show); longendTime=System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } }catch(DocumentExceptione){ e.printStackTrace(); } } publicstaticvoidread3(){ /* *setDocumentFactory()namespace(setXPathNamespaceURIs) */ try{ longstartTime=System.currentTimeMillis(); Mapmap=newHashMap(); map.put("Workbook","urn:schemas-microsoft-com:office:spreadsheet"); SAXReaderreader=newSAXReader(); InputStreamin=TestDom4jXpath.class.getClassLoader().getResourceAsStream("XPath\\XXX.xml"); reader.getDocumentFactory().setXPathNamespaceURIs(map); Documentdoc=reader.read(in); Stringxpath="//Workbook:Row[4]/Workbook:Cell[3]/Workbook:Data[1]"; System.err.println("=====usesetXPathNamespaceURIs()tosetDocumentFactory()namespace===="); System.err.println("XPath:"+xpath); @SuppressWarnings("unchecked") List<Element>list=doc.selectNodes(xpath); for(Objecto:list){ Elemente=(Element)o; Stringshow=e.getStringValue(); System.out.println("show="+show); longendTime=System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } }catch(DocumentExceptione){ e.printStackTrace(); } } publicstaticvoidread4(){ /* *同read3()方法一样,但是XPath表达式不同 */ try{ longstartTime=System.currentTimeMillis(); Mapmap=newHashMap(); map.put("Workbook","urn:schemas-microsoft-com:office:spreadsheet"); SAXReaderreader=newSAXReader(); InputStreamin=TestDom4jXpath.class.getClassLoader().getResourceAsStream("XPath\\XXX.xml"); reader.getDocumentFactory().setXPathNamespaceURIs(map); Documentdoc=reader.read(in); Stringxpath="//Workbook:Worksheet/Workbook:Table/Workbook:Row[4]/Workbook:Cell[3]/Workbook:Data[1]"; System.err.println("=====usesetXPathNamespaceURIs()tosetDocumentFactory()namespace===="); System.err.println("XPath:"+xpath); @SuppressWarnings("unchecked") List<Element>list=doc.selectNodes(xpath); for(Objecto:list){ Elemente=(Element)o; Stringshow=e.getStringValue(); System.out.println("show="+show); longendTime=System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } }catch(DocumentExceptione){ e.printStackTrace(); } } publicstaticvoidread5(){ /* *DOMandXPath */ try{ longstartTime=System.currentTimeMillis(); DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(false); DocumentBuilderbuilder=dbf.newDocumentBuilder(); InputStreamin=TestDom4jXpath.class.getClassLoader().getResourceAsStream("XPath\\XXX.xml"); org.w3c.dom.Documentdoc=builder.parse(in); XPathFactoryfactory=XPathFactory.newInstance(); javax.xml.xpath.XPathx=factory.newXPath(); //选取所有class元素的name属性 Stringxpath="//Workbook/Worksheet/Table/Row[4]/Cell[3]/Data[1]"; System.err.println("=====DomXPath===="); System.err.println("XPath:"+xpath); XPathExpressionexpr=x.compile(xpath); NodeListnodes=(NodeList)expr.evaluate(doc,XPathConstants.NODE); for(inti=0;i<nodes.getLength();i++){ System.out.println("show="+nodes.item(i).getNodeValue()); longendTime=System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } }catch(XPathExpressionExceptione){ e.printStackTrace(); }catch(ParserConfigurationExceptione){ e.printStackTrace(); }catch(SAXExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } }
更多java使用xpath和dom4j解析xml相关文章请关注PHP中文网!

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











この記事では、XML属性値の変更、整形式、スキーマ/DTD検証、および文字エンコードに起因する制限の強調を詳しく説明しています。 不適切な脱出やデータ型の不一致のような落とし穴を強調し、証言に対処します

この記事では、RSSフィードを使用して効率的なニュース集約とコンテンツキュレーションを使用する方法について説明します。 RSSリーダー(FeedlyやInoreaderなど)を使用して、フィードを使用し、フィードの整理、ターゲットコンテンツの機能を活用する詳細を説明します。 ベネ

XMLコンテンツの変更は、特に大きなファイルでアプリケーションのパフォーマンスに大きく影響します。 解析、DOM操作、シリアル化、およびI/O操作がこれに貢献します。 最適化戦略には、ストリーミングパーサーの使用、dの最小化が含まれます

この記事は、効率的な大規模なXMLファイルの変更に取り組んでいます。 これは、メモリ処理の非効率性を強調し、SAXやStaxの解析などのストリーミングアプローチを提唱しています。 最適化のための戦略には、増分解析、最適化されたデータが含まれます

この記事では、RSSフィードを使用してコンテンツシンジケーションの実装を詳しく説明しています。 RSSフィードの作成、ターゲットWebサイトの識別、フィードの送信、および監視の有効性をカバーしています。 制限されたコントロールや豊富なメディアサポートなどの課題も円盤投げです

この記事では、XMLデータ変換方法について詳しく説明しています。 XMLドキュメント内のデータ形式を変換する際の課題に対処し、XSLTやストリーム処理などの効率的な手法を強調しています。 この記事は、Schなどの潜在的な落とし穴についてもカバーしています

この記事では、XMLとセマンティックWebテクノロジーの統合について説明します。 コアの問題は、セマンティックの相互運用性のためにXMLの構造化データをRDFトリプルにマッピングすることです。 ベストプラクティスには、オントロジーの定義、戦略的マッピングアプローチ、慎重なattが含まれます

この記事では、Webコンテンツ管理のためのAtom Publishing Protocol(Atompub)について説明します。 コンテンツの作成、検索、更新、および削除のためのAtom形式を使用して、HTTPメソッド(Get、Post、Put、Delete)を使用して詳細を説明します。 この記事では、Atompubについても説明します
