以下程序正确解析 xml 文件并显示其 name 元素值和 rel 的链接属性值。我想将这两个值存储在 ArrayList <UserDetail>
用户详细信息类:
public class UserDetail {
private String name;
private String mailid;
public String getMailid() {
return mailid;
}
public void setMailid(String mailid) {
this.mailid = mailid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
SAX 解析类:
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean link = false;
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("fullName")) {
name = true;
}
if (qName.equalsIgnoreCase("link")) {
System.out.println("\t" + attributes.getValue("rel"));
}
}
public void endElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("fullName")) {
name = false;
}
if (qName.equalsIgnoreCase("link")) {
link = false;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (name) {
System.out.println("First Name : " + new String(ch, start, length));
name = false;
}
}
};
saxParser.parse("D://abc.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
XML 文档:
<feed>
<entry>
<fullName>Manish Sahu</fullName>
<link rel='abc'/>
<link rel='self'/>
<link rel='edit'/>
</entry>
</feed>