<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE poems[
<!ELEMENT poems (poem*)>
<!ELEMENT poem (title,author,year?,content)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT content (#PCDATA)>
]>
<poems>
<poem>
<title>清明</title>
<author>杜牧</author>
<content>
清明时节雨纷纷,
路上行人欲断魂.
借问酒家何处是,
牧童遥指杏花村.
</content>
</poem>
<poem>
<title>声声慢-寻寻觅觅</title>
<author>李清照</author>
<content>
寻寻觅觅,冷冷清清,凄凄惨惨戚戚。
乍暖还寒时候,最难将息。
三杯两盏淡酒,怎敌他、晚来风急?
雁过也,正伤心,却是旧时相识。
满地黄花堆积。憔悴损,如今有谁堪摘?
守着窗儿,独自怎生得黑?
梧桐更兼细雨,到黄昏、点点滴滴。
这次第,怎一个愁字了得!
</content>
</poem>
</poems>
java代码部分
package com.parseXML;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParsePoems {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
/**
* 获取dom工厂对象
*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
/**
* 获取domBuilder对象
*/
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db
.parse("G:\\ZONGFUXI\\parse_XML\\src\\com\\xml\\poems.xml");
NodeList poems = dom.getElementsByTagName("poem");
Node poem = poems.item(0);
System.out.println(poem.getChildNodes().getLength());//结果为7
}
}
为什么打印出来后,第一首poem的子节点一共有7个?不应该是3个吗?
------解决思路----------------------
楼主虽然自己已经找到了问题的解决方案,但是还是建议楼主 满意结贴 ,这样还能返回一半的可用分,要是无满意结贴 ,20分就都没了。