2014-10-07 80 views
0

我有一個xml,我需要解析並從中獲取值。但是,我不確定哪種解析方式對於這種類型的xml來說是最好的。我閱讀了不同的方式,但不確定這是否是最好的方式。有人可以幫我寫一個Java代碼來解析這個XML使用最好的方法? 在此先感謝!使用XPath/DOM/SAX解析XML

這裏的XML:

<managementDomain> 
    <mtosi:additionalInfo> 
      <mtosi:nvs> 
       <stru:attributeName>Managed Device Name</stru:attributeName> 
       <stru:attributeValue> 
        <nonc:value>al-dcdc-numr-phe-eu</nonc:value> 
       </stru:attributeValue> 
      </mtosi:nvs> 
      <mtosi:nvs> 
       <stru:attributeName>NMDBF</stru:attributeName> 
       <stru:attributeValue> 
        <nonc:value>Y</nonc:value> 
       </stru:attributeValue> 
      </mtosi:nvs> 
      <mtosi:nvs> 
       <stru:attributeName>BFGCustrID</stru:attributeName> 
       <stru:attributeValue> 
        <nonc:value>3444</nonc:value> 
       </stru:attributeValue> 
      </mtosi:nvs> 
      <mtosi:nvs> 
       <stru:attributeName>BFGContractID</stru:attributeName> 
       <stru:attributeValue> 
        <nonc:value>12331</nonc:value> 
       </stru:attributeValue> 
      </mtosi:nvs> 
     </mtosi:additionalInfo> 
    <mtosi:mdVendorExtensions> 
     <mtosi:tmf854Version/> 
     <mtosi:extVersion/> 
     <mtosi:extAuthor/> 
    </mtosi:mdVendorExtensions> 
    <mtosi:managedElement> 
     <mtosi:manufacturer> 
      <nonc:ossValue>CISCO</nonc:ossValue> 
     </mtosi:manufacturer> 
     <mtosi:productName> 
      <nonc:value>CISCO2951</nonc:value> 
     </mtosi:productName> 
     <mtosi:meVendorExtensions> 
      <mtosi:tmf854Version/> 
      <mtosi:extVersion/> 
      <mtosi:extAuthor/> 
      <mtosi:managementIPAddress> 
       <mtosi:ipValue> 
        <nonc:value>10.32.22.49</nonc:value> 
       </mtosi:ipValue> 
      </mtosi:managementIPAddress> 
     </mtosi:meVendorExtensions> 
    </mtosi:managedElement> 
</managementDomain> 

我需要獲取:

ManagementIpAddress,BFGCustomerId,BFGContractID和託管設備名稱從這個XML解析這個XML的

+0

使用['元素#的getElementsByTagName()'](HTTP://文檔。 oracle.com/javase/7/docs/api/org/w3c/dom/Element.html#getElementsByTagName%28java.lang.String%29)使用其名稱獲取標籤元素。 – Braj 2014-10-07 08:02:08

+0

你的問題不適合SO,因爲它主要是基於意見的。您可以使用您提及的所有技術,以及您使用的所有技術都取決於您以及您的要求和技能。任何技術都應該爲這種簡單的XML做好準備。此外,我們不爲您提供完整的代碼 - 請先嚐試一下,如果遇到問題,我們很樂意爲您提供幫助。 – dirkk 2014-10-07 08:33:25

+0

@dirkk - 如果您可以幫助,並感謝您寶貴的建議,我打破了我的頭,直到這裏!需要您的專家建議對上述查詢請 – 2014-10-09 11:13:07

回答

1

兩種可能的方式是DOM4J和SAX。前者的內存密集程度更高,並將完整的文檔加載到Java對象結構中。使用SAX,您可以通過流式處理內容並「聆聽」您要提取的元素來解析文件。

因此,對於您的具體情況 - 即只讀幾個元素 - SAX可能是要走的路。

SAX的缺點是,它會引入一些只適用於特定的並且正確(即在最好的情況下經過預先驗證的)XML文件的黑客解決方案。使用SAX時,您需要更仔細地編程。

(當然小個XML它不是一個恥辱與DOM4J完全地加載它,如果這是你更方便;)