java XML用DOM解析,遍历时标签为空,无法遍历子元素。

发布于:2023-01-04 ⋅ 阅读:(547) ⋅ 点赞:(0)
<?xml version="1.0" encoding="UTF-8" ?>
<woman>
    <young name="年轻的">
        <Age age="18岁妹子"></Age>
        <Age age ="19岁妹子"></Age>
    </young>
    <young name="漂亮的">
        <Age age="175漂亮妹子"></Age>
        <Age age="180漂亮妹子"></Age>
    </young>
</woman>

以上是XML文件内容。

public class XML {
    Document document =null;
    //获取Document对象
    public void getDocument() throws ParserConfigurationException, IOException, SAXException {
        //解析工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //解析器
        DocumentBuilder builder =factory.newDocumentBuilder();
        //获取对象
        document =builder.parse("src/cn/like_code/like_zuoye/zuoye823/mz.xml");
    }
//查询XML文件
public void showInfo(){
    //查找标签
    NodeList young = document.getElementsByTagName("young");
    //循环
    for (int i = 0; i < young.getLength(); i++) {
        Node youngnode = young.item(i);
        Element eleyoung=(Element)youngnode;
        System.out.println(eleyoung.getAttribute("name"));
        NodeList age = eleyoung.getChildNodes();
        for (int j = 0; j < age.getLength(); j++) {
            Node agenode = age.item(i);
            if (agenode.getNodeType()==Node.ELEMENT_NODE) {
                Element eleage = (Element) agenode;
                System.out.println(eleage.getAttribute("age"));
            }
        }
    }

//main方法调用

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
    XML xml = new XML();
    xml.getDocument();
    xml.showInfo();
}
运行结果:
年轻的
漂亮的
175漂亮妹子
175漂亮妹子
175漂亮妹子
175漂亮妹子
175漂亮妹子

大神帮忙!!!!谢谢。