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();
}
上一篇:【译】2021年国外十大AI自动写作软件评测


下一篇:C# winform点击生成二维码