Java教程

Java常用代码实现——解析xml

本文主要是介绍Java常用代码实现——解析xml,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

pom依赖:

<!--引入dom4j-->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

解析xml:

/**
  *  读取并修改xml文件
  */
public boolean modifyXmlElement(String filePath, String channelId, String bookId) {
    try {
        // 创建SAXReader对象,关联xml
        SAXReader sr = new SAXReader();
        Document document = sr.read(filePath);

        // 获取根元素,遍历application标签下的子标签
        Element root = document.getRootElement();
        Iterator iter = root.element("application").elementIterator();
        while (iter.hasNext()) {
            Element element = (Element) iter.next();
            // 读取xml属性
            String elementValue = element.attribute(0).getValue();

            // 修改xml属性
            if ("DK_DIST_CHANNEL".equals(elementValue) ||
                    "UMENG_CHANNEL".equals(elementValue)) {
                Attribute att = element.attribute(1);
                att.setValue(channelId);
            }
            if (StringUtils.isNotBlank(bookId) &&
                    "INNER_BOOK_ID".equals(elementValue)) {
                Attribute att = element.attribute(1);
                att.setValue(bookId);
            }
        }

        saveDocument(document, new File(filePath));
    } catch (Exception e) {
        ScribeLogger.error(logEvent, "modify xml file, occur exception, %s", e);
        return false;
    }
    return true;
}


/**
 * 保存对xml文件的修改
 */
public void saveDocument(Document document, File xmlFile) throws IOException {
    ScribeLogger.info(logEvent, "save document, xml file path, %s", xmlFile);

    Writer outWrite = new OutputStreamWriter(new FileOutputStream(xmlFile));
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");

    XMLWriter writer = new XMLWriter(outWrite, format);
    writer.write(document);
    writer.flush();
    writer.close();
}
这篇关于Java常用代码实现——解析xml的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!