日期:2014-05-17  浏览次数:20713 次

怎么解析XML,要源码
怎么解析XML,要源码

------解决方案--------------------
InputStream in = Controller.class.getClassLoader().getResourceAsStream("./XML的文件名");
Properties per = new Properties();
per.load(in);
String myAction = per.getProperty(键值); 
得到的就是value了
------解决方案--------------------
可以用开源组件,比如 dom4j 啥的,也有性能更高的。

不过本质都差不多,用Xpath查找或者按节点依次便利。

这里有个稍微复杂的参考(需要dom4j):
Java code

        String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                + "<soap:Body><ACIC_MessageBrokerService xmlns=\"http://www.ACIC.MessageBrokerService.com/\">"
                + "<ServiceID>0428000001</ServiceID>" + "<obj>" + "<anyType xsi:type=\"xsd:string\">par1</anyType>"
                + "<anyType xsi:type=\"xsd:int\">0</anyType>" + "<anyType xsi:type=\"xsd:boolean\">true</anyType>"
                + "</obj></ACIC_MessageBrokerService>" + "</soap:Body>" + "</soap:Envelope>";
        Document doc = DocumentHelper.parseText(str);
        Element root = doc.getRootElement();
        System.out.println(root);
        Element node = root.element("Body").element("ACIC_MessageBrokerService").element("ServiceID");
        System.out.println(node.getName() + ": " + node.getText());

        Element obj = root.element("Body").element("ACIC_MessageBrokerService").element("obj");
        List<Element> types = obj.elements("anyType");
        for (Element elem : types) {
            System.out.println(elem.getName() + ": " + elem.getText());
        }

        System.out.println(root.selectSingleNode("soap:Body"));
        System.out
                .println(doc
                        .selectSingleNode("//*[local-name()='ServiceID' and namespace-uri()='http://www.ACIC.MessageBrokerService.com/']"));

        List<Element> lstType = doc
                .selectNodes("//*[local-name()='anyType' and namespace-uri()='http://www.ACIC.MessageBrokerService.com/']");
        for (Element elem : lstType) {
            System.out.println(elem.getName() + ": " + elem.getText());
        }