[英]How to use java to get element of xml document, but in xml string format?
我已經閱讀了一些有關解析xml文檔的鏈接,如下所示:
<inventory>
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<!-- more books... -->
</inventory>
使用DOM解析:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
但是,它們的目的主要是通過文檔中的標簽或屬性來獲取某些節點的VALUE 。
我的目的是找回節點的整個XML STRING 。 例如,使用Xpath / inventory / book [@ year ='2005'],我想將以下xml返回到單個字符串中,即
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
用於此目的的API是什么? 在這種情況下,我甚至需要DOM解析嗎? 謝謝,
評論:
也許我應該強調,我在問這個問題是與XML相關的問題,而不是文本文件處理問題。 “標記”,“屬性”,“ Xpath”等概念仍然適用。 DOM模型並非完全無關緊要。 只是要獲得整個節點,而不是獲得節點的“元素”或值。
給定的答案不能解決以下問題:給定節點的Xpath表示形式,例如//book
或/inventory/book[1]
,如何以xml字符串格式獲取節點?
DOM解析器旨在從其中獲取值,而不是針對實際文件內容。
您可以使用簡單的文件讀取器代替XML。
使用一個簡單的FileReader
逐行讀取並檢查該行是否滿足條件,如果滿足該條件,則根據需要啟動要連接的讀取內容,直到節點結束。
你可以做到
if(lineReadFromFile=="Your String Condition"){
//collect the desired file content here untill the end of the Node is found
}
您可以使用FileReader從文件中讀取XML(將其視為普通文本文件)。 簡單應用條件例如:
if(line.equals("<book year="2005"><title>Burning Tower</title>")) {
// retrieve/save the required content
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.