[code=Java]
import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import org.w3c.dom.CharacterData;
public class XMLParse { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建File的对象file,用来在内存中加载XML文件
File file = new File("E:\\Demo.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
try{
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
Element element1 = doc.getDocumentElement();
String str = element1.getNodeName();
System.out.println(str);
NodeList list = element1.getElementsByTagName("name");
int n = list.getLength();
for (int i = 0; i < n; i++) {
Node node = list.item(i);
String value = node.getNodeValue();
System.out.println(value);
}
} catch (Exception e) {
// TODO: handle exception
}
}}
[/Java]xml文件是:
<?xml version="1.0" encoding="gb2312"?>
<people>
  <person>
    <name>zhang san</name>
    <sex>male</sex>
    <age>24</age>
  </person>
  <person>
    <name>li si</name>
    <sex>male</sex>
    <age>19</age>
  </person>
</people>

解决方案 »

  1.   

    w3c的这个读取XML很不给力,用的不是很舒服,平时自己用jdom最多,dom4j也不错,你这里输出的为null是调用的API不对,给你看下面的程序就有值输出了
    package csdn.p6;import java.io.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.*;
    import org.w3c.dom.CharacterData;public class XMLParse {    /**
         * @param args
         */
        public static void main(String[] args) {
    // TODO Auto-generated method stub
    //创建File的对象file,用来在内存中加载XML文件
            File file = new File("E:\\Demo.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            try{
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(file);
                Element element1 = doc.getDocumentElement();            NodeList list=element1.getChildNodes();
    //            System.out.println(list.getLength());
    //            NodeList list = element1.getElementsByTagName("person");
                int n = list.getLength();
                System.out.println("输出元素有"+n+"个");
                for (int i = 0; i < n; i++) {
                    Node node = list.item(i);
                    String value = node.getTextContent();
                    if(!value.trim().isEmpty())
                        System.out.println("值输出"+value);
                }
            } catch (Exception e) {
    // TODO: handle exception
                e.printStackTrace();
            }
        }}
      

  2.   

     try{
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(file);
                Element element1 = doc.getDocumentElement();            NodeList list=element1.getChildNodes();
    //            System.out.println(list.getLength());
    //            NodeList list = element1.getElementsByTagName("person");
                int n = list.getLength();
                System.out.println("输出元素有"+n+"个");
                for (int i = 0; i < n; i++) {
                    Node node = list.item(i);
                    String value = node.getTextContent();
                    if(!value.trim().isEmpty())
                        System.out.println("值输出"+value);
                }
            } catch (Exception e) {
    // TODO: handle exception
                e.printStackTrace();
            }
      

  3.   

    import java.io.*;
    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 Hao { public static void main(String[] args) {
    // 创建File的对象file,用来在内存中加载XML文件
    File file = new File("F:\\Demo.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file);
    Element element1 = doc.getDocumentElement();
    String str = element1.getNodeName();
    System.out.println(str);
    NodeList list = element1.getChildNodes();
    int n = list.getLength();
    for (int i = 0; i < n; i++) {
    Node node1 = list.item(i);
    if (node1.getNodeType() == Node.ELEMENT_NODE) { for (Node node = node1.getFirstChild(); node != null; node = node
    .getNextSibling()) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
    if (node.getNodeName().equals("name")) {
    String name1 = node.getFirstChild()
    .getNodeValue();
    System.out.println(name1);
    }
    if (node.getNodeName().equals("sex")) {
    String price = node.getFirstChild()
    .getNodeValue();
    System.out.println(price);
    }
    }
    }
    }
    }
    } catch (Exception e) {
    // TODO: handle exception
    }
    }
    }
      

  4.   

    怎么才能使输出是
    people
    zhang san 
    li si
      

  5.   


    我知道楼主的意思,用一般的XML遍历方法其实可以,2L 3L的代码小改一下可以,不过如果楼主想要一下子遍历所有的person子元素的name列表,其实要用X-Path的技术,所以我没在楼主基础上做,重新写一个Demo这个Demo比较优雅,而且你再添加元素也会动态输出
    import java.io.IOException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;public class XPathExampleDemo {  public static void main(String[] args)
       throws ParserConfigurationException, SAXException,
              IOException, XPathExpressionException {    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("e:\\Demo1.xml");    XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr
         = xpath.compile("//person/name/text()");    Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }  }}