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");
}
}
<?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");
}
}
BS一下
<root>
<person name="" phone="" sex=""/>
<person name="" phone="" sex=""/>
</root>这个也是标准的xml,用文本逐行读取分析。
<root>
<person name="" phone="" sex=""/>
<person name="" phone="" sex=""/>
</root> 这个也是标准的xml,用文本逐行读取分析。
Dom4j实现很简单