如何用java来获取xml文档的元素,但是用xml字符串格式?

时间:2015-12-30 03:22:38

标签: java xml dom

我已经阅读了一些解析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解析吗?谢谢,

COMMENT:

也许我应该强调,我将此问题视为与XML相关的问题,而不是文本文件处理问题。像'tag','attribute','Xpath'这样的概念仍然适用。 DOM模型并非完全无关紧要。它只是不是获取节点的'元素'或值,而是想获得整个节点。

给定的答案无法解决以下问题:如果在节点的Xpath表示中给出节点的xml字符串格式,如//book/inventory/book[1]

2 个答案:

答案 0 :(得分:0)

DOM解析器旨在从中获取值而不是实际文件内容。

您可以使用简单的文件阅读器而不是XML。

使用简单的FileReader逐行读取并检查条件的行,如果满足条件,则启动读取内容,直到节点结束为止。

你可以这样做

if(lineReadFromFile=="Your String Condition"){
    //collect the desired file content here untill the end of the Node is found
}

答案 1 :(得分:0)

您可以使用 FileReader 从文件中读取XML(将其视为普通文本文件)。简单应用条件例如:

if(line.equals("<book year="2005"><title>Burning Tower</title>")) {
     // retrieve/save the required content
}