ksding 发表于 2012-08-11 10:46

java解析xml的疑问


XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
    <book category="COOKING">
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
    </book>
    <book category="XXXX">
            <title lang="en2">Learning XML2</title>
            <author>Erik T. Ray2</author>
            <year>20032</year>
            <price>39.952</price>
    </book>
</bookstore>

Java:
        public static void readXML2(String xmlFile) {
                try {
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Document doc = db.parse(xmlFile);
                        Element root = doc.getDocumentElement();// root 指向bookstore节点
                        NodeList nls = root.getChildNodes();// nls指向bookstore的子节点book
                        System.out.println(nls.getLength());


为什么输出的长度是5呢?不是很明白。
另外如果是这样的xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
    <book category="COOKING">
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
    </book>
    <book category="XXXX">
            <title lang="en2">Learning XML2</title>
            <author>Erik T. Ray2</author>
            <year>20032</year>
            <price>39.952</price>
            <book category="ddddd">
                    <title lang="en3">Learning XML3</title>
                    <author>Erik T. Ray3</author>
                    <year>20033</year>
                    <price>39.95</price>
            </book>
    </book>
</bookstore>

试了网上的几个解析方法,基本都会将<book category="ddddd">这个下面的内容丢掉,
这个不是很合理的xml该如何解析?

谢谢


页: [1]
查看完整版本: java解析xml的疑问