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)

ホットトピック









Mobile XMLからPDFへの速度は、次の要因に依存します。XML構造の複雑さです。モバイルハードウェア構成変換方法(ライブラリ、アルゴリズム)コードの品質最適化方法(効率的なライブラリ、アルゴリズムの最適化、キャッシュデータ、およびマルチスレッドの利用)。全体として、絶対的な答えはなく、特定の状況に従って最適化する必要があります。

単一のアプリケーションで携帯電話でXMLからPDF変換を直接完了することは不可能です。クラウドサービスを使用する必要があります。クラウドサービスは、2つのステップで達成できます。1。XMLをクラウド内のPDFに変換し、2。携帯電話の変換されたPDFファイルにアクセスまたはダウンロードします。

携帯電話でXMLをPDFに直接変換するのは簡単ではありませんが、クラウドサービスの助けを借りて実現できます。軽量モバイルアプリを使用してXMLファイルをアップロードし、生成されたPDFを受信し、クラウドAPIで変換することをお勧めします。クラウドAPIはサーバーレスコンピューティングサービスを使用し、適切なプラットフォームを選択することが重要です。 XMLの解析とPDF生成を処理する際には、複雑さ、エラー処理、セキュリティ、および最適化戦略を考慮する必要があります。プロセス全体では、フロントエンドアプリとバックエンドAPIが連携する必要があり、さまざまなテクノロジーをある程度理解する必要があります。

web.xmlファイルを開くには、次の方法を使用できます。テキストエディター(メモ帳やテキストエディットなど)を使用して、統合開発環境(EclipseやNetBeansなど)を使用してコマンドを編集できます(Windows:Notepad web.xml; Mac/Linux:Open -A Textedit Web.xml)

XMLフォーマットツールは、読みやすさと理解を向上させるために、ルールに従ってコードを入力できます。ツールを選択するときは、カスタマイズ機能、特別な状況の処理、パフォーマンス、使いやすさに注意してください。一般的に使用されるツールタイプには、オンラインツール、IDEプラグイン、コマンドラインツールが含まれます。

XMLをPDFに直接変換するアプリケーションは、2つの根本的に異なる形式であるため、見つかりません。 XMLはデータの保存に使用され、PDFはドキュメントを表示するために使用されます。変換を完了するには、PythonやReportLabなどのプログラミング言語とライブラリを使用して、XMLデータを解析してPDFドキュメントを生成できます。

ほとんどのテキストエディターを使用して、XMLファイルを開きます。より直感的なツリーディスプレイが必要な場合は、酸素XMLエディターやXMLSPYなどのXMLエディターを使用できます。プログラムでXMLデータを処理する場合、プログラミング言語(Pythonなど)やXMLライブラリ(XML.ETREE.ELEMENTTREEなど)を使用して解析する必要があります。

XMLオンラインフォーマットツールは、厄介なXMLコードを自動的に読みやすい形式と維持します。 XMLの構文ツリーを解析し、フォーマットルールを適用することにより、これらのツールはコードの構造を最適化し、その保守性とチームワークの効率を向上させます。
