繁体   English   中英

如何使用Java获取xml文档的元素,但以xml字符串格式?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM