按照题目要求编写的Item父类的Java程序如下
public class Item{
private String goods
private int unitperbox
public Item(String goods,int unitperbox){
this.goods=goods
this.unitperbox=unitperbox
}
public String ShowGoods(){
return goods
}
public int ShowUnitPerBox(){
return unitperbox
}
}
例子是将XML保存在D盘根目录下,名字为:test.xmlimport java.io.IOException
import java.util.ArrayList
import java.util.List
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.SAXException
class Item{
private String id
private String type
private String label
private String url
private String description
public String getId() {
return id
}
public void setId(String id) {
this.id = id
}
public String getType() {
return type
}
public void setType(String type) {
this.type = type
}
public String getLabel() {
return label
}
public void setLabel(String label) {
this.label = label
}
public String getUrl() {
return url
}
public void setUrl(String url) {
this.url = url
}
public String getDescription() {
return description
}
public void setDescription(String description) {
this.description = description
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer()
sb.append("item: ")
if(getId()!=null &&!"".equals(getId())){
sb.append("id = ").append(getId()).append(",")
}
if(getType()!=null &&!"".equals(getType())){
sb.append("type = ").append(getType()).append(",")
}
if(getLabel()!=null &&!"".equals(getLabel())){
sb.append("label = ").append(getLabel()).append(",")
}
if(getUrl()!=null &&!"".equals(getUrl())){
sb.append("url = ").append(getUrl()).append(",")
}
if(getDescription()!=null &&!"".equals(getDescription())){
sb.append("description = ").append(getDescription()).append(",")
}
return sb.toString()
}
}
public class TestXML {
/**
*
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
List<Item>itemList = new ArrayList<Item>()
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
Document doc = docBuilder.parse("D:\\test.xml")
NodeList nodeList = doc.getElementsByTagName("item")
for(int i=0i<nodeList.getLength()i++){
Node node = nodeList.item(i)
if(node.getNodeType() == Node.ELEMENT_NODE){
Element el = (Element) node
Item item = new Item()
item.setId(el.getAttribute("id"))
item.setType(el.getAttribute("type"))
item.setLabel(el.getAttribute("label"))
item.setUrl(el.getAttribute("url"))
item.setDescription(el.getAttribute("description"))
itemList.add(item)
}
}
System.out.println("------------")
for(Item item:itemList){
System.out.println(item)
}
}
}