好记性不如烂笔头60-利用XMLConfiguration解析XML多节点

前端之家收集整理的这篇文章主要介绍了好记性不如烂笔头60-利用XMLConfiguration解析XML多节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

利用XMLConfiguration解析XML多节点.

1、 用XMLConfiguration解析XML多节点的源代码

package test.ffm83.commons.configuration;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.HierarchicalConfiguration.Node;
import org.apache.commons.configuration.XMLConfiguration;

/** * 简单示例,解析XML多个同类型子节点属性,比如输出XY坐标 * * @author 范芳铭 */
public class EasyParseNodesXML {
    //解析子节点
    private static String parseMutliLines(HierarchicalConfiguration lineConfig) {
        String value = "";
        Node root = lineConfig.getRoot();
        List children = root.getChildren();

        int count = 0;
        for (int i = 0; i < children.size(); i++) {
            Node child = (Node) children.get(i);
            if ("point".equals(child.getName())) {
                count++;
            }
        }
        for (int i = 0; i < count; i++) {
            value += lineConfig.getString("point(" + i + ")[@X]");
            value += ",";
            value += lineConfig.getString("point(" + i + ")[@Y]");
            value += ":";
        }
        return value;
    }

    public static void main(String[] args) throws Exception {
        String xml = "<csMsgReqs>"
                + " <csMsgReq xsi:type=\"cstypeNotify\">"
                + " <authority xsi:type=\"cstypeAuthorityCommon\"/>"
                + " <nbase xsi:type=\"cstypeAlarmGeneral\">"
                + " <alarmTime>2014-03-21 16:16:26.682</alarmTime>"
                + " <TrackLine xsi:type=\"cstypeTrackLineType\" lineLth=\"18\">"
                + " <point xsi:type=\"cstypepoint\" X=\"1211\" Y=\"351\"/>"
                + " <point xsi:type=\"cstypepoint\" X=\"1386\" Y=\"472\"/>"
                + " </TrackLine>" + " </nbase>"
                + " </csMsgReq>" + "</csMsgReqs>";

        InputStream in = new ByteArrayInputStream(xml.getBytes());
        XMLConfiguration config = new XMLConfiguration();

        try {
            config.load(in);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String alarmTime = config.getString("csMsgReq.nbase.alarmTime");
        //将子节点作为参数传入
        HierarchicalConfiguration lineConfig = (HierarchicalConfiguration) config
                .subset("csMsgReq.nbase.TrackLine");
        String trackLine = parseMutliLines(lineConfig);

        System.out.println("alarmTime:" + alarmTime);
        System.out.println("trackLine:" + trackLine);
    }
}

2、 运行程序

alarmTime:2014-03-21 16:16:26.682 trackLine:1211,351:1386,472:

原文链接:https://www.f2er.com/xml/297104.html

猜你在找的XML相关文章