日期:2014-05-20  浏览次数:20896 次

DOM解析xml的问题
xml代码
<?xml version="1.0"?>
<animals>
<animal>
<name>tiger</name>
<weight>500 pounds</weight>
<length>3 yard from nose to tail</length>
</animal>
<animal>
<name>rhino</name>
<weight>900 pounds</weight>
<length>9 yard from nose to tail</length>
</animal>
<animal>
<name>pp</name>
<weight>900sdfsdf pounds</weight>
<length>sdfsdfsdfsdfsdfs yard from nose to tail</length>
</animal>
</animals>
java代码
public class dom {

/**
 * @param args
 * @throws ParserConfigurationException 
 * @throws IOException 
 * @throws SAXException 
 */
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO Auto-generated method stub
 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document doc = builder.parse(new File("d/animal.xml"));
      
/////////////////插入节点////////////////////////////////////////
        Element animals= null;
        Element animal = null;
        Element name = null;
        Element weight = null;
        Element length = null;
        NodeList list = doc.getElementsByTagName("animals");
        animals = (Element)list.item(0);
        
        animal = doc.createElement("animal");
        
        
        name = doc.createElement("name");
        name.appendChild(doc.createTextNode("nnnnnn"));
        animal.appendChild(name);
        
        weight = doc.createElement("weight");
        weight.appendChild(doc.createTextNode("111111111111"));
        animal.appendChild(weight);
        
        length = doc.createElement("length");
        length.appendChild(doc.createTextNode("123123"));
        animal.appendChild(length);
        

        animals.appendChild(animal);
        ////////////////////////////////////////////
        NodeList n1 = doc.getElementsByTagName("animal");
        for(int i=0; i<n1.getLength(); i++) {