java之xml新手教程

-1.网上的教程为什么都是这么老的教程,难道是我的搜索方式有问题??

使用for遍历,使用equals,这效率不敢想象啊。

0.使用包:xmlbeans-2.3.0.jar

1.xml文本



<module>
    <ommbFtp>
        <ip>10ip>
        <port>21port>
        <userName>auserName>
        <passWord>bpassWord>
    ommbFtp>

    <database>
        <ip>12ip>
        <port>1521port>
        <userName>systemuserName>
        <passWord>123456passWord>
        <instance>oracleinstance>
    database>

module>

2.显示xml

2.1获取根节点

package utils;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PaseXml {
    /*
     * element.getNodeName(),获取节点名
     * (element  | Node) .getChildNodes(),获取节点下的子节点list,返回NodeList
     * node.getAttributes().getNamedItem("type").getNodeValue(),节点属性键对应的值
     */
    public static void main(String[] args) throws Exception {
        ShowXml();
    }
    public static void ShowXml() throws Exception{
        String filePath = "conf/ommbNOData.xml";
        FileInputStream fis = new FileInputStream(filePath);
        //获取所需的4个对象:文档构建工厂,文档构建,文档,(根)元素
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(fis);
        Element element = document.getDocumentElement();
        //获得子节点list,for遍历,获得孙节点,for遍历,得到孙节点的元素
        System.out.println("根元素:" + element.getNodeName()); // 获得根节点
        NodeList sonNodes = element.getChildNodes(); // 获得根元素下的子节点
        for (int i = 0; i < sonNodes.getLength(); i++) // 遍历这些子节点
        {
            Node sonNode = sonNodes.item(i); 
            NodeList grandsonNodes = sonNode.getChildNodes(); // 获得下的节点
            for (int j = 0; j < grandsonNodes.getLength(); j++) { // 遍历下的节点
                Node grandsonNode = grandsonNodes.item(j); // 获得元素每一个节点
                if ("ip".equals(grandsonNode.getNodeName())) // 输出code
                    System.out.println("ip: " + grandsonNode.getTextContent());
                else if ("port".equals(grandsonNode.getNodeName()))
                    System.out.println("port: " + grandsonNode.getTextContent());
                else if ("userName".equals(grandsonNode.getNodeName()))
                    System.out.println("userName: " + grandsonNode.getTextContent());
                else if ("passWord".equals(grandsonNode.getNodeName()))
                    System.out.println("passWord: " + grandsonNode.getTextContent());
            }
        }
    }
}

你可能感兴趣的:(xml)