如何使用java以xml字符串格式获取xml文档的元素?
我已经阅读了一些有关解析xml文档的链接,如下所示:如何使用java以xml字符串格式获取xml文档的元素?,java,xml,dom,Java,Xml,Dom,我已经阅读了一些有关解析xml文档的链接,如下所示: <inventory> <book year="2000"> <title>Snow Crash</title> <author>Neal Stephenson</author> <publisher>Spectra</publisher> <isbn>055338
<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>
雪崩
尼尔·斯蒂芬森
光谱
0553380958
14.95
燃烧塔
拉里·尼文
杰里·波内尔
口袋
0743416910
5.99
使用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>);
DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
Document doc=builder.parse();
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile();
然而,它们的目的主要是通过标签或属性从文档中获取某些节点的值
我的目的是获取节点的整个XML字符串。例如,使用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>
燃烧塔
拉里·尼文
杰里·波内尔
口袋
0743416910
5.99
用于此目的的API是什么?在这种情况下,我甚至需要DOM解析吗?谢谢
评论:
也许我应该强调,我问这个问题是一个与XML相关的问题,而不是一个文本文件处理问题。“标记”、“属性”、“Xpath”等概念仍然适用。DOM模型并非完全无关。只是我不想得到节点的“元素”或值,而是想得到整个节点
给定的答案无法解决这样的问题:如何以xml字符串格式获取节点,给定节点的Xpath表示,例如
//book
或/inventory/book[1]
?DOM解析器被设计为从节点获取值,而不是实际的文件内容
您可以使用简单的文件读取器而不是XML
使用简单的文件读取器
逐行读取,并检查该行的条件,如果满足条件,则根据需要将读取内容启动到concat,直到节点结束
你可以照我说的做
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
}
if(行等于(“燃烧塔”)){
//检索/保存所需的内容
}