//DOM方式
package com.neusoft.xml;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomXmlSample {
/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// TODO Auto-generated method stub
// 1.获得一个新DocumentBuilderFactory实例(定义工厂API,使应用程序能够从 XML 文档获取生成 DOM
// 对象树的解析器)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 2.使用DocumentBuilderFactory构建DocumentBuilder(定义 API, 使其从 XML 文档获取 DOM
// 文档实例。使用此类,应用程序员可以从 XML 获取一个 Document)
DocumentBuilder db = dbf.newDocumentBuilder();
// 3.使用DocumentBuilder的parse()方法解析文件
// 4.将已解析的文档存储在Document对象中
Document document = db.parse("testDocument.xml");
// 5.使用getElementsByTagName()方法获得元素
NodeList bookList = document.getElementsByTagName("book");
// 获取所有的子节点
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("========第" + i + "记录============");
Node node = bookList.item(i);
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childN = childNodes.item(j);
if (childN.getFirstChild() != null) {
System.out.print(childN.getNodeName());
System.out.println(":"
+ childN.getFirstChild().getNodeValue());
}
}
}
}
}
package com.neusoft.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class JdomXmlSample {
/**
* @param args
* @throws IOException
* @throws JDOMException
*/
public static void main(String[] args) throws JDOMException, IOException {
// TODO Auto-generated method stub
SAXBuilder builder=new SAXBuilder(false);//表示使用默认的解析器
Document document=builder.build("testDocument.xml");
Element root=document.getRootElement();
List books=root.getChildren("book");
for(int i=0;i
{
Element book=(Element)books.get(i);
Element code=book.getChild("code");
Element title=book.getChild("title");
Element author=book.getChild("author");
Element price=book.getChild("price");
System.out.println("code="+code.getText()+"\t"+"title="+title.getText()
+"\tauthor="+author.getText()+"\t"+"price="+price.getText());
// System.out.println("code:"+book.getChildText("code")+
// "\ttitle:"+book.getChildText("title")
// +"\tauthor:"+book.getChildText("author")+
// "\tprice:"+book.getChildText("price"));
book.getChild("price").setText("100");
}
XMLOutputter outputter=new XMLOutputter();
outputter.output(document, new FileOutputStream("abc.xml"));
}
}
a.xml
]>
男
abc.xml
1
张三
100
2
李四
100
3
王五
100
testDocument.xml
1
张三
100
2
李四
100
3
王五
100
xmltest.dtd