info.xml
<?xml version="1.0" encoding="UTF-8"?> 
<infos>
<info>
<name>张三</name>
<phone>12322121</phone>
<sex>男</sex>
</info>
<info>
<name>李四</name>
<phone>23322121</phone>
<sex>女</sex>
</info>
</infos>
代码可以参考一下import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class DomParseXml {
    private static void parseXml(String xmlFile) {
        try {
            File f = new File(xmlFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("info");
            String name = null;
            String phone = null;
            String sex = null;
            for (int i = 0; i < nl.getLength(); i++) {
                name = doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
                phone = doc.getElementsByTagName("phone").item(i).getFirstChild().getNodeValue();
                sex = doc.getElementsByTagName("sex").item(i).getFirstChild().getNodeValue();
                System.out.println(name.trim() + " phone is " + phone.trim()+" sex is " + sex.trim()+"address is address" + i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    public static void main(String[] args) {
        parseXml("info.xml");
    }
}

解决方案 »

  1.   

    1楼的写得不错,不过可以考虑用Jdom或者dom4j,会更简单一些。
      

  2.   

    个人感觉这样的 面试题 没什么意思。都是API上的东西,不可能凭借记忆去实现。
    BS一下
      

  3.   

    xml可以写
    <root>
    <person name="" phone="" sex=""/>
    <person name="" phone="" sex=""/>
    </root>这个也是标准的xml,用文本逐行读取分析。
      

  4.   

    xml可以写 
    <root> 
    <person name="" phone="" sex=""/> 
    <person name="" phone="" sex=""/> 
    </root> 这个也是标准的xml,用文本逐行读取分析。
    Dom4j实现很简单