XML节点当做文本处理

XmlHelper类中封装的方法,采用JDOM实现。

 

如下所示:

   /**
     * 输出XML文件流。根据指定的编码,将输入的节点,输出到输出流中。
     * @param xml XML文件流
     * @return xml JDOM树的根节点,如果XML格式错误,返回空(null)
     * @throws JDOMException
     */
    public static void output(Writer writer, Element root, String encoding) {
        encoding = (encoding == null ? UTF8 : encoding);
        Document doc = new Document(root);
        XMLOutputter outputter = new XMLOutputter();
        Format format = Format.getPrettyFormat();
        format.setEncoding(encoding);
        outputter.setFormat(format);
        try {
            writer.write(outputter.outputString(doc));
        } catch (IOException e) {
            throw new SystemException(String.format("输出节点[%s]时出现错误。", root.toString()));
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                logger.warn("关闭输出流时出现错误。", e);
            }
        }
    }

  

   //将节点数据提取成Text字符串返回

   public static String getElementText(Element element){
        if (element != null) {
            Element tempElement = (Element) element.clone();

            StringWriter sw = new StringWriter();
            XmlHelper.output(sw, tempElement, null);
            String s = sw.toString();
        }
        return null;
    }

 

/**
     * 传入XML字符串,返回XML的根节点。
     * @param xml XML字符串
     * @return xml JDOM树的根节点,如果XML格式错误,返回空(null)
     * @throws JDOMException
     * @throws IOException
     */
    public static Element getRootFromString(String xml) throws JDOMException,
            IOException {
        if (xml == null) {
            return null;
        }
        LogWriter.debug(logger, "XmlHelper getRootFromString xml=" + xml);
        Document doc = null;
        SAXBuilder builder = new SAXBuilder(); //解析器
        doc = builder.build(new StringReader(xml));
        if (doc != null) {
            return doc.getRootElement();
        }
        return null;
    }

 

调用示例:

        String styleText= XmlHelper.getElementText(element);

 

        Element root = XmlHelper.getRootFromString(styleText);

你可能感兴趣的:(xml)