??xml version="1.0" encoding="utf-8" standalone="yes"?> JDOM是一个开源项目,它基于树型结构,利用UJAVA的技术对XML文实现解析、生成、序列化以及多种操作?/P>
JDOM 直接为JAVA~程服务。它利用更ؓ强有力的JAVA语言的诸多特性(Ҏ重蝲、集合概念以及映)Q把SAX和DOM的功能有效地l合h?/P>
在用设计上可能地隐藏原来使用XMLq程中的复杂性。利用JDOM处理XML文是一件轻松、简单的事?/P>
JDOM ?000q的春天被Brett McLaughlin和Jason Hunter开发出来,以I补DOM及SAX在实际应用当中的不之处?/P>
q些不之处主要在于SAX没有文档修改、随问以及输出的功能Q而对于DOM来说QJAVAE序员在使用时来用v来总觉得不太方ѝ?/P>
DOM的缺点主要是来自于由于Dom是一个接口定义语aQIDLQ?它的d是在不同语言实现中的一个最低的通用标准Qƈ不是为JAVA特别设计的。JDOM的最新版本ؓJDOM Beta 9。最qJDOM被收录到JSR-102内,q标志着JDOM成ؓ了JAVAq_l成的一部分?/P>
二、JDOM 包概?/P>
JDOM是由以下几个包组成的 org.jdom.filter 包含了xml文的过滤器c?/P>
org.jdom.input 包含了读取xml文的类 org.jdom.output 包含了写入xml文的类 org.jdom.transform 包含了将jdom xml文接口转换为其他xml文接口 org.jdom.xpath 包含了对xml文xpath操作的类三、JDOM c说?/P>
1、org.JDOMq个包里的类是你J解析xml文g后所要用到的所有数据类型?/P>
Attribute CDATA Coment DocType Document Element EntityRef Namespace ProscessingInstruction Text 2、org.JDOM.transform在涉及xslt格式转换时应使用下面?个类 JDOMSource JDOMResult org.JDOM.input 3、输入类Q一般用于文档的创徏工作 SAXBuilder DOMBuilder ResultSetBuilder org.JDOM.output 4、输出类Q用于文{换输?/P>
XMLOutputter SAXOutputter DomOutputter JTreeOutputter 使用前注意事: 1.JDOM对于JAXP 以及 TRax 的支?/P>
JDOM 支持JAXP1.1Q你可以在程序中使用M的parser工具c?默认情况下是JAXP的parser?/P>
制定特别的parser可用如下形式 SAXBuilder parser = new SAXBuilder("org.apache.crimson.parser.XMLReaderImpl"); Document doc = parser.build("
// work with the document... JDOM也支持TRaXQXSLT可通过JDOMSource以及JDOMResultcL转换Q参见以后章节) 2.注意在JDOM里文档(DocumentQ类由org.JDOM.Document 来表C。这要与org.w3c.dom中的Document区别开Q这2U格式如何{换在后面会说明?/P>
以下如无Ҏ均指JDOM里的Document?/P>
四、JDOM主要使用Ҏ 1.Ducumentc?/P>
(1)Document的操作方法: Element root = new Element("GREETING"); Document doc = new Document(root); root.setText("Hello JDOM!"); 或者简单的使用Document doc = new Document(new Element("GREETING").setText("Hello JDOM!t")); q点和DOM不同。Dom则需要更为复杂的代码Q如下: DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder builder =factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element root =doc.createElement("root"); Text text = doc.createText("This is the root"); root.appendChild(text); doc.appendChild(root); 注意事项QJDOM不允许同一个节点同时被2个或多个文档相关联,要在W?个文中使用原来老文中的节点的话。首先需要用detach()把这个节点分开来?/P>
(2)从文件、流、系lID、URL得到Document对象Q?/P>
DOMBuilder builder = new DOMBuilder(); Document doc = builder.build(new File("jdom_test.xml")); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(url); 在新版本中DOMBuilder 已经Deprecated?DOMBuilder.builder(url)Q用SAX效率会比较快?/P>
q里举一个小例子Qؓ了简单v见,使用String对象直接作ؓxml数据源: public jdomTest() { String textXml = null; textXml = "<note>"; textXml = textXml + "<to>aaa</to><from>bbb</from><heading>ccc</heading><body>ddd</body>"; textXml = textXml + "</note>"; SAXBuilder builder = new SAXBuilder(); Document doc = null; Reader in= new StringReader(textXml); try { doc = builder.build(in); Element root = doc.getRootElement(); List ls = root.getChildren();//注意此处取出的是root节点下面的一层的Element集合 for (Iterator iter = ls.iterator(); iter.hasNext(); ) { Element el = (Element) iter.next(); if(el.getName().equals("to")){ System.out.println(el.getText()); } } } catch (IOException ex) { ex.printStackTrace(); } catch (JDOMException ex) { ex.printStackTrace(); } } (3)DOM的document和JDOM的Document之间的相互{换用方法,单! DOMBuilder builder = new DOMBuilder(); org.jdom.Document jdomDocument = builder.build(domDocument); DOMOutputter converter = new DOMOutputter();// work with the JDOM document?/P>
org.w3c.dom.Document domDocument = converter.output(jdomDocument); // work with the DOM document?/P>
2.XML文档输出 XMLOutPutterc: JDOM的输出非常灵z?支持很多Uio格式以及风格的输?/P>
Document doc = new Document(...); XMLOutputter outp = new XMLOutputter(); outp.output(doc, fileOutputStream); // Raw output outp.setTextTrim(true); // Compressed output outp.output(doc, socket.getOutputStream()); outp.setIndent(" ");// Pretty output outp.setNewlines(true); outp.output(doc, System.out); 详细请参阅最新的JDOM API手册 3.Element c: (1)览Element?/P>
Element root = doc.getRootElement();//获得根元素element List allChildren = root.getChildren();// 获得所有子元素的一个list List namedChildren = root.getChildren("name");// 获得指定名称子元素的list Element child = root.getChild("name");//获得指定名称的第一个子元素 JDOMl了我们很多很灵zȝ使用Ҏ来管理子元素Q这里的List是java.util.ListQ?/P>
List allChildren = root.getChildren(); allChildren.remove(3); // 删除W四个子元素 allChildren.removeAll(root.getChildren("jack"));// 删除叫“jack”的子元?/P>
root.removeChildren("jack"); // 便捷写法 allChildren.add(new Element("jane"));// 加入 root.addContent(new Element("jane")); // 便捷写法 allChildren.add(0, new Element("first")); (2)UdElements: 在JDOM里很?/P>
Element movable = new Element("movable"); parent1.addContent(movable); // place parent1.removeContent(movable); // remove parent2.addContent(movable); // add 在Dom?/P>
Element movable = doc1.createElement("movable"); parent1.appendChild(movable); // place parent1.removeChild(movable); // remove parent2.appendChild(movable); // 出错! 补充Q纠错?/P>
JDOM的Element构造函敎ͼ以及它的其他函数Q会查element是否合法?/P>
而它的add/removeҎ会检查树l构Q检查内容如下: 1.在Q何树中是否有回环节点 2.是否只有一个根节点 3.是否有一致的命名I间QNamespacesQ? (3)Element的text内容d <description> A cool demo </description> // The text is directly available // Returns "\n A cool demo\n" String desc = element.getText(); // There's a convenient shortcut // Returns "A cool demo" String desc = element.getTextTrim(); (4)Elment内容修改 element.setText("A new description"); 3.可正解释特D字W?/P>
element.setText("<xml> content"); 4.CDATA的数据写入、读?/P>
element.addContent(new CDATA("<xml> content")); String noDifference = element.getText(); 混合内容 element可能包含很多U内容,比如?/P>
<table> <!-- Some comment --> Some text <tr>Some child element</tr> </table> 取table的子元素tr String text = table.getTextTrim(); Element tr = table.getChild("tr"); 也可使用另外一个比较简单的Ҏ List mixedCo = table.getContent(); Iterator itr = mixedCo.iterator(); while (itr.hasNext()) { Object o = i.next(); if (o instanceof Comment) {...} // q里可以写成Comment, Element, Text, CDATA,ProcessingInstruction, 或者是EntityRef的类?/P>
} // 现在U除Comment,注意q里游标应ؓ1。这是由于回车键也被解析成Textcȝ~故,所以Comment应??/P>
mixedCo.remove(1); 4.Attributec?/P>
<table width="100%" border="0"> </table> String width = table.getAttributeValue("width");//获得attribute int border = table.getAttribute("width").getIntValue(); table.setAttribute("vspace", "0");//讄attribute table.removeAttribute("vspace");// 删除一个或全部attribute table.getAttributes().clear(); 5.处理指o(Processing Instructions)操作 一个Pls的例?/P>
<?br?> <?cocoon-process type="xslt"?> | | | | 目标 数据 处理目标名称(Target) String target = pi.getTarget(); 获得所有数据(dataQ,在目标(targetQ以后的所有数据都会被q回?/P>
String data = pi.getData(); String type = pi.getValue("type");获得指定属性的数据 List ls = pi.getNames();获得所有属性的名称 6.命名I间操作 <xhtml:html xmlns:xhtml="
<xhtml:title>Home Page</xhtml:title> </xhtml:html> Namespace xhtml = Namespace.getNamespace("xhtml", "
List kids = html.getChildren("title", xhtml); Element kid = html.getChild("title", xhtml); kid.addContent(new Element("table", xhtml)); 7.XSLT格式转换 使用以下函数可对XSLT转换 最后如果你需要用w3c的Document则需要{换一下?/P>
public static Document transform(String stylesheetQDocument in) throws JDOMException { try { Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(stylesheet)); JDOMResult out = new JDOMResult(); transformer.transform(new JDOMSource(in), out); return out.getDeocument(); } catch (TransformerException e) { throw new JDOMException("XSLT Trandformation failed", e); } } 五、用? 1、生成xml文档Q?/P>
public class WriteXML{ public void BuildXML() throws Exception { Element root,student,number,name,age; root = new Element("student-info"); //生成根元素:student-info student = new Element("student"); //生成元素Qstudent(number,name,age) number = new Element("number"); name = new Element("name"); age = new Element("age"); Document doc = new Document(root); //根元素植入文档doc?/P>
number.setText("001"); name.setText("lnman"); age.setText("24"); student.addContent(number); student.addContent(name); student.addContent(age); root.addContent(student); Format format = Format.getCompactFormat(); format.setEncoding("gb2312"); //讄xml文g的字Wؓgb2312 format.setIndent(" "); //讄xml文g的羃qؓ4个空?/P>
XMLOutputter XMLOut = new XMLOutputter(format);//元素后换行一层元素羃四格 XMLOut.output(doc, new FileOutputStream("studentinfo.xml")); } public static void main(String[] args) throws Exception { WriteXML w = new WriteXML(); System.out.println("Now we build an XML document ....."); w.BuildXML(); System.out.println("finished!"); } } 生成的xml文为: <?xml version="1.0" encoding="gb2312"?> <student-info> <student> <number>001</number> <name>lnman</name> <age>24</age> </student> </student-info> 创徏XML文档2Q?/P>
public class CreateXML { public void Create() { try { Document doc = new Document(); ProcessingInstruction pi=new ProcessingInstruction("xml-stylesheet","type="text/xsl" href="test.xsl""); doc.addContent(pi); Namespace ns = Namespace.getNamespace("
Namespace ns2 = Namespace.getNamespace("other", "
Element root = new Element("根元?, ns); root.addNamespaceDeclaration(ns2); doc.setRootElement(root); Element el1 = new Element("元素一"); el1.setAttribute("属?, "属性一"); Text text1=new Text("元素?); Element em = new Element("元素?).addContent("W二个元?); el1.addContent(text1); el1.addContent(em); Element el2 = new Element("元素?).addContent("W三个元?); root.addContent(el1); root.addContent(el2); //~进四个I格,自动换行,gb2312~码 XMLOutputter outputter = new XMLOutputter(" ", true,"GB2312"); outputter.output(doc, new FileWriter("test.xml")); }catch(Exception e) { System.out.println(e); } } public static void main(String args[]) { new CreateXML().Create(); } } 2、读取xml文档的例子: import org.jdom.output.*; import org.jdom.input.*; import org.jdom.*; import java.io.*; import java.util.*; public class ReadXML{ public static void main(String[] args) throws Exception { SAXBuilder builder = new SAXBuilder(); Document read_doc = builder.build("studentinfo.xml"); Element stu = read_doc.getRootElement(); List list = stu.getChildren("student"); for(int i = 0;i < list.size();i++) { Element e = (Element)list.get(i); String str_number = e.getChildText("number"); String str_name = e.getChildText("name"); String str_age = e.getChildText("age"); System.out.println("---------STUDENT--------------"); System.out.println("NUMBER:" + str_number); System.out.println("NAME:" + str_name); System.out.println("AGE:" + str_age); System.out.println("------------------------------"); System.out.println(); } } } 3、DTD验证的: public class XMLWithDTD { public void validate() { try { SAXBuilder builder = new SAXBuilder(true); builder.setFeature("); Document doc = builder.build(new FileReader("author.xml")); System.out.println("搞掂"); XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, System.out); }catch(Exception e) { System.out.println(e); } } public static void main(String args[]) { new XMLWithDTD().validate(); } } 需要说明的是,q个E序没有指明使用哪个DTD文g。DTD文g的位|是在XML中指定的Q而且DTD不支持命名空_一个XML只能引用一个DTDQ所以程序直接读取XML中指定的DTDQ程序本w不用指定。不q这样一来,好象只能用外部式的DTD引用方式了?高h指点?/P>
4、XML Schema验证的: public class XMLWithSchema { String xml="test.xml"; String schema="test-schema.xml"; public void validate() { try { SAXBuilder builder = new SAXBuilder(true); //指定U束方式为XML schema builder.setFeature("
//导入schema文g builder.setProperty("); Document doc = builder.build(new FileReader(xml)); System.out.println("搞掂"); XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, System.out); }catch(Exception e) { System.out.println("验证p|:"+e); } } } 上面的程序就指出了要引入的XML Schema文g的位|?/P>
pȝ默认输出是UTF-8Q这有可能导致出Cؕ码?/P>
5、Xpath例子Q?/P>
JDOM的关于XPATH的api在org.jdom.xpathq个包里。这个包下,有一个抽象类XPath.java和实现类JaxenXPath.javaQ?使用时先用XPathcȝ静态方法newInstance(String xpath)得到XPath对象Q然后调用它的selectNodes(Object context)Ҏ或selectSingleNode(Object context)ҎQ前者根据xpath语句q回一l节?List对象)Q后者根据一个xpath语句q回W合条g的第一个节?Objectcd)。请看jdom-1.0自带的范例程序: 它分析在web.xml文g中的注册的servlet的个数及参数个数Qƈ输出角色名? web.xml文gQ? <?xml version="1.0" encoding="ISO-8859-1"?> <!-- <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
org.jdom 包含了所有的xml文要素的javac?BR>
org.jdom.adapters 包含了与dom适配的javac?/P>
2、DTD验证的:
需要说明的是,q个E序没有指明使用哪个DTD文g。DTD文g的位|是在XML中指定的Q而且DTD不支持命名空_一个XML只能引用一个DTDQ所以程序直接读取XML中指定的DTDQ程序本w不用指定。不q这样一来,好象只能用外部式的DTD引用方式了?高h指点?/P>
3、XML Schema验证的:
上面的程序就指出了要引入的XML Schema文g的位|?/P>
pȝ默认输出是UTF-8Q这有可能导致出Cؕ码?/P>
读XML文的技巧在|上已经泛滥Q这里就没有再列出来?/P>