<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pets [
<!ELEMENT pets (dogs,penguins)>
<!ELEMENT dogs (dog*)>
<!ELEMENT penguins (penguin+)>
<!ELEMENT dog(name,health,love,strain?)>
<!ATTLIST dog id CDATA #REQUIRED>
<!ELEMENT penguin(name,health,love,sex)>
<!ATTLIST penguin id CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT health (#PCDATA)>
<!ELEMENT love (#PCDATA)>
<!ELEMENT strain (#PCDATA)>
<!ELEMENT sex (#PCDATA)>
]>
<pets>
<dogs>
<dog id="1">
<name>111</name>
<health>100</health>
<love>0</love>
<strain>藏獒</strain>
</dog>
<dog id="2">
<name>222</name>
<health>91</health>
<love>9</love>
<strain>土狗</strain>
</dog>
</dogs>
<penguins>
<penguin id="1">
<name>QQ</name>
<health>1000</health>
<love>1000</love>
<sex>Q妞</sex>
</penguin>
</penguins>
</pets>
-----------------------------------------------------------------------
public static void main(String[] args) {
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc= db.parse("pet2.xml");
NodeList loglist=doc.getElementsByTagName("dog");
System.out.println("xml文件里面共有"+loglist.getLength()+"狗狗的信息");
for(int i=0;i<loglist.getLength();i++){
}
}catch(Exception e){
e.printStackTrace();
}
}
-------------------------------------------------------------------
报错。[Fatal Error] pet2.xml:6:14: White space is required after the element type "dog" in the element type declaration.
org.xml.sax.SAXParseException: White space is required after the element type "dog" in the element type declaration.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
at T14.t14_1.main(t14_1.java:14)
------解决方案--------------------------------------------------------
少了两个空格
- XML code
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE pets [<!ELEMENT pets (dogs,penguins)><!ELEMENT dogs (dog*)><!ELEMENT penguins (penguin+)><!ELEMENT dog (name,health,love,strain?)><!ATTLIST dog id CDATA #REQUIRED><!ELEMENT penguin (name,health,love,sex)><!ATTLIST penguin id CDATA #REQUIRED><!ELEMENT name (#PCDATA)><!ELEMENT health (#PCDATA)><!ELEMENT love (#PCDATA)><!ELEMENT strain (#PCDATA)><!ELEMENT sex (#PCDATA)>]><pets> <dogs> <dog id="1"> <name>111</name> <health>100</health> <love>0</love> <strain>藏獒</strain> </dog> <dog id="2"> <name>222</name> <health>91</health> <love>9</love> <strain>土狗</strain> </dog> </dogs> <penguins> <penguin id="1"> <name>QQ</name> <health>1000</health> <love>1000</love> <sex>Q妞</sex> </penguin> </penguins></pets>
------解决方案--------------------------------------------------------