XPathFactory返回xml文档

时间:2014-10-05 16:26:26

标签: java xpath

我想通过XPathFactory从xml文档中列出一些节点,但我得到的是没有xml节点的纯文本 我的Xml文档是这样的:

<?xml version="1.0" encoding="utf-8"?>
<journal>
<title>Hakim Research Journal</title>
<subject>Medical Sciences</subject>

<articleset>
<article>
<title>Challenges and Performance Improvement Approaches of Boards of Trustees of Universities of Medical Sciences and Health Services </title>
<content_type>Original</content_type>
</article>
<article>

<title>  Risk Factors of Infant Mortality Rate in North East of Iran </title>
<content_type>Original</content_type>
</article>

</articleset>
</journal>

我想要回报元素,如下:

    <article>
        <title>Challenges and Performance Improvement Approaches of Boards of Trustees of         Universities of Medical Sciences and Health Services in Iran </title>
<content_type>Original</content_type>
</article>
<article>
<title>  Risk Factors of Infant Mortality Rate in North East</title>
<content_type>Original</content_type>
</article>

我的代码实现是:

String result="";
File xmlDocument = new File("e://journal_last.xml");
InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
XPathFactory  factory=XPathFactory.newInstance();
XPath xPath=factory.newXPath();
XPathExpression articleset;
articleset = xPath.compile("/journal/articleset/)");
result =   articleset.evaluate(inputSource);
System.out.println(result); 

但它只返回没有节点标签的节点的纯文本! 输出是:

Challenges and Performance Improvement Approaches of Boards of Trustees of Universities of     Medical Sciences and Health Services  
Original



Risk Factors of Infant Mortality Rate in North East  
Original
你能帮帮我吗? 我感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以评估XPath上的Document来获取文章的NodeList,然后将NodeList写为xml。

public class Main {

    public static void main(String[] args) throws Exception {
        File xmlDocument = new File("e://journal_last.xml");
        FileInputStream xmlInputStream = new FileInputStream(xmlDocument);

        Document doc = parseDocument(new InputSource(xmlInputStream));
        NodeList articleList = evaluateXPath(doc, "/journal/articleset",
                NodeList.class);
        String xmlString = writeXmlString(articleList);

        System.out.println(xmlString);

    }

    private static Document parseDocument(InputSource inputSource)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document doc = docBuilder.parse(inputSource);
        return doc;
    }

    @SuppressWarnings("unchecked")
    private static <T> T evaluateXPath(Document doc, String xpath,
            Class<T> resultType) throws XPathExpressionException {
        QName returnType = resolveReturnType(resultType);

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        XPathExpression xpathExpression = xPath.compile(xpath);

        Object resultObject = xpathExpression.evaluate(doc, returnType);
        return (T) resultObject;
    }

    private static QName resolveReturnType(Class<?> clazz) {
        if (NodeList.class.equals(clazz)) {
            return XPathConstants.NODESET;
        } else {
            throw new UnsupportedOperationException("Not implemented yet");
        }
    }

    private static String writeXmlString(NodeList nodeList)
            throws TransformerConfigurationException,
            TransformerFactoryConfigurationError, TransformerException {

        StreamResult streamResult = new StreamResult(new StringWriter());
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node articleListItem = nodeList.item(i);
            DOMSource source = new DOMSource(articleListItem);
            transformer.transform(source, streamResult);
        }

        String xmlString = streamResult.getWriter().toString();
        return xmlString;
    }
}