写了简单的dom4j的使用的demo,以备回忆,有些是dom4j的文挡里例子改编的
使用dom4j解析下面的xml文件。
Xml代码
167 version="1.0"encoding="GB2312" >
168
169 type="text/xsl"href="students.xsl" >
170
171
172
173
174
175
176
177
178
179
180
181
Parse.java
Java代码
182 import java.io.File;
183
184 import org.dom4j.Attribute;
185 import org.dom4j.Document;
186 import org.dom4j.DocumentException;
187 import org.dom4j.Element;
188 import org.dom4j.ProcessingInstruction;
189 import org.dom4j.VisitorSupport;
190 import org.dom4j.io.SAXReader;
191
192 publicclass Parse {
193
194 publicstaticvoid main(String[] args) {
195 SAXReader reader = new SAXReader();
196 File file = new File("src/students.xml");
197 try {
198 Document doc = reader.read(file);
199 doc.accept(new MyVistor());
200 } catch (DocumentException e) {
201 // TODO Auto-generated catch block
202 e.printStackTrace();
203 }
204 }
205
206 publicstaticclass MyVistor extends VisitorSupport {
207 publicvoid visit(Attribute node) {
208 System.out.println("Attibute:---" + node.getName() + "="+ node.getValue());
209 }
210
211 publicvoid visit(Element node) {
212 if (node.isTextOnly()) {
213 System.out.println("Element:---" + node.getName() + "="
214 + node.getText());
215 }else{
216 System.out.println("--------" + node.getName() + "-------");
217 }
218 }
219
220 @Override
221 publicvoid visit(ProcessingInstruction node) {
222 System.out.println("PI:"+node.getTarget()+" "+node.getText());
223 }
224 }
225 }
使用dom4j来将属性写入xml
Java代码
226 import java.io.FileWriter;
227 import java.io.IOException;
228
229 import org.dom4j.Document;
230 import org.dom4j.DocumentHelper;
231 import org.dom4j.Element;
232 import org.dom4j.io.OutputFormat;
233 import org.dom4j.io.XMLWriter;
234
235 publicclass DWriter {
236
237 publicstaticvoid main(String[] args) {
238 // TODO Auto-generated method stub
239 try {
240 XMLWriter writer = new XMLWriter(new FileWriter("src/author.xml"));
241 Document doc = createDoc();
242 writer.write(doc);
243 writer.close();
244
245 // Pretty print the document to System.out
246 // 设置了打印的格式,将读出到控制台的格式进行美化
247 OutputFormat format = OutputFormat.createPrettyPrint();
248 writer = new XMLWriter(System.out, format);
249 writer.write(doc);
250
251 } catch (IOException e) {
252 // TODO Auto-generated catch block
253 e.printStackTrace();
254 }
255 }
256
257 publicstatic Document createDoc() {
258 Document doc = DocumentHelper.createDocument();
259 Element root = doc.addElement("root");
260 Element author1 = root.addElement("author").addAttribute("name",
261 "Kree").addAttribute("location", "UK")
262 .addText("Kree Strachan");
263 Element author2 = root.addElement("author").addAttribute("name", "King")
264 .addAttribute("location", "US").addText("King McWrirter");
265 return doc;
266 }
267 }
使用dom4j写入到author.xml文件的内容
Java代码
268
269
270
271
272