java是如何解析xml文档的,如何实现java编辑xml文档?java如何读取xml文档?给个例子说明一下最好。谢谢!
解决方案 »
- preparedStatement与createStatemt优缺点对比
- 【迷宫问题】大家帮我看下这个这段代码,或者帮忙写个迷宫算法
- 求助!如何读写另一台机器上的文件?
- 给定的几个数字,怎么样排序找到最大的一个呢?
- [请斑竹进来一下]好好的回复为什么不允许?
- 用java如何以二进制的形式判断一个文件是pdf或word或excel?
- 关于从JTable删除一行数据遇到的问题
- JDialog的显示位置的问题
- 新手求解
- 加了按键或其他后,为什么APPLET程序生成的HTML在JBUILDER8中可以看到有变化,而在外面用浏览器看却没变化呢?出现了出现了class united.
- 请问,怎样调整panel的大小?
- 想要做一个游戏……
One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.import java.net.URL;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;public class Foo { public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
}
A document can be navigated using a variety of methods that return standard Java Iterators. For example public void bar(Document document) throws DocumentException { Element root = document.getRootElement(); // iterate through child elements of root
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
} // iterate through child elements of root with element name "foo"
for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
Element foo = (Element) i.next();
// do something
} // iterate through attributes of root
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
}
private String userName = "";
private String passWord = "";
private Document doc = null;
public GetConfig(){}
public Document getDoc(){
SAXReader sr = new SAXReader();
try {
doc = sr.read(new File("user-config.xml"));
//doc = sr.read(this.getClass().getClassLoader().getResource(("user-config.xml")));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("读取失败");
}
return doc;
}
public void readConfig(){
this.getDoc();
List<Element> nameList = doc.selectNodes("/users/user/name");
List<Element> passWordList = doc.selectNodes("/users/user/password");
userName = nameList.get(0).getText();
passWord = passWordList.get(0).getText();
System.out.println(userName + passWord);
}
public static void main(String[] args){
GetConfig gc = new GetConfig();
gc.readConfig();
}
public String getUserName(){
return this.userName;
}
public String getPassWord(){
return this.passWord;
}
}采用xpath方式读取,建议LZ先熟悉一下dom结构。
你也可以用开源的XStream,
Java对象转换为xml文件,xml文件再转换为Java对象。