涓銆丣DOM 綆浠?/p>
JDOM鏄竴涓紑婧愰」鐩紝瀹冨熀浜庢爲鍨嬬粨鏋勶紝鍒╃敤綰疛AVA鐨勬妧鏈XML鏂囨。瀹炵幇瑙f瀽銆佺敓鎴愩佸簭鍒楀寲浠ュ強澶氱鎿嶄綔銆?/p>
JDOM 鐩存帴涓篔AVA緙栫▼鏈嶅姟銆傚畠鍒╃敤鏇翠負寮烘湁鍔涚殑JAVA璇█鐨勮澶氱壒鎬э紙鏂規硶閲嶈澆銆侀泦鍚堟蹇典互鍙婃槧灝勶級錛屾妸SAX鍜孌OM鐨勫姛鑳芥湁鏁堝湴緇撳悎璧鋒潵銆?/p>
鍦ㄤ嬌鐢ㄨ璁′笂灝藉彲鑳藉湴闅愯棌鍘熸潵浣跨敤XML榪囩▼涓殑澶嶆潅鎬с傚埄鐢↗DOM澶勭悊XML鏂囨。灝嗘槸涓浠惰交鏉俱佺畝鍗曠殑浜嬨?/p>
JDOM 鍦?000騫寸殑鏄ュぉ琚獴rett McLaughlin鍜孞ason Hunter寮鍙戝嚭鏉ワ紝浠ュ譏琛OM鍙奡AX鍦ㄥ疄闄呭簲鐢ㄥ綋涓殑涓嶈凍涔嬪銆?/p>
榪欎簺涓嶈凍涔嬪涓昏鍦ㄤ簬SAX娌℃湁鏂囨。淇敼銆侀殢鏈鴻闂互鍙婅緭鍑虹殑鍔熻兘錛岃屽浜嶥OM鏉ヨ錛孞AVA紼嬪簭鍛樺湪浣跨敤鏃舵潵鐢ㄨ搗鏉ユ昏寰椾笉澶柟渚褲?/p>
DOM鐨勭己鐐逛富瑕佹槸鏉ヨ嚜浜庣敱浜嶥om鏄竴涓帴鍙e畾涔夎璦錛圛DL錛?瀹冪殑浠誨姟鏄湪涓嶅悓璇█瀹炵幇涓殑涓 涓渶浣庣殑閫氱敤鏍囧噯錛屽茍涓嶆槸涓篔AVA鐗瑰埆璁捐鐨勩侸DOM鐨勬渶鏂扮増鏈負JDOM Beta 9銆傛渶榪慗DOM琚敹褰曞埌JSR-102鍐咃紝榪欐爣蹇楃潃JDOM鎴愪負浜咼AVA騫沖彴緇勬垚鐨勪竴閮ㄥ垎銆?/p>
浜屻丣DOM 鍖呮瑙?/p>
JDOM鏄敱浠ヤ笅鍑犱釜鍖呯粍鎴愮殑
org.jdom 鍖呭惈浜嗘墍鏈夌殑xml鏂囨。瑕佺礌鐨刯ava綾?/p>
org.jdom.adapters 鍖呭惈浜嗕笌dom閫傞厤鐨刯ava綾?/p>
org.jdom.filter 鍖呭惈浜唜ml鏂囨。鐨勮繃婊ゅ櫒綾?/p>
org.jdom.input 鍖呭惈浜嗚鍙杧ml鏂囨。鐨勭被
org.jdom.output 鍖呭惈浜嗗啓鍏ml鏂囨。鐨勭被
org.jdom.transform 鍖呭惈浜嗗皢jdom xml鏂囨。鎺ュ彛杞崲涓哄叾浠杧ml鏂囨。鎺ュ彛
org.jdom.xpath 鍖呭惈浜嗗xml鏂囨。xpath鎿嶄綔鐨勭被涓夈丣DOM 綾昏鏄?/p>
1銆乷rg.JDOM榪欎釜鍖呴噷鐨勭被鏄綘J瑙f瀽xml鏂囦歡鍚庢墍瑕佺敤鍒扮殑鎵鏈夋暟鎹被鍨嬨?/p>
Attribute
CDATA
Coment
DocType
Document
Element
EntityRef
Namespace
ProscessingInstruction
Text
2銆乷rg.JDOM.transform鍦ㄦ秹鍙妜slt鏍煎紡杞崲鏃跺簲浣跨敤涓嬮潰鐨?涓被
JDOMSource
JDOMResult
org.JDOM.input
3銆佽緭鍏ョ被錛屼竴鑸敤浜庢枃妗g殑鍒涘緩宸ヤ綔
SAXBuilder
DOMBuilder
ResultSetBuilder
org.JDOM.output
4銆佽緭鍑虹被錛岀敤浜庢枃妗h漿鎹㈣緭鍑?/p>
XMLOutputter
SAXOutputter
DomOutputter
JTreeOutputter
浣跨敤鍓嶆敞鎰忎簨欏癸細
1.JDOM瀵逛簬JAXP 浠ュ強 TRax 鐨勬敮鎸?/p>
JDOM 鏀寔JAXP1.1錛氫綘鍙互鍦ㄧ▼搴忎腑浣跨敤浠諱綍鐨刾arser宸ュ叿綾?榛樿鎯呭喌涓嬫槸JAXP鐨刾arser銆?/p>
鍒跺畾鐗瑰埆鐨刾arser鍙敤濡備笅褰㈠紡
SAXBuilder parser
= new SAXBuilder("org.apache.crimson.parser.XMLReaderImpl");
Document doc = parser.build("http://www.cafeconleche.org/");
// work with the document...
JDOM涔熸敮鎸乀RaX錛歑SLT鍙氳繃JDOMSource浠ュ強JDOMResult綾繪潵杞崲錛堝弬瑙佷互鍚庣珷鑺傦級
2.娉ㄦ剰鍦↗DOM閲屾枃妗o紙Document錛夌被鐢眔rg.JDOM.Document 鏉ヨ〃紺恒傝繖瑕佷笌org.w3c.dom涓殑Document鍖哄埆寮錛岃繖2縐嶆牸寮忓浣曡漿鎹㈠湪鍚庨潰浼氳鏄庛?/p>
浠ヤ笅濡傛棤鐗規寚鍧囨寚JDOM閲岀殑Document銆?/p>
鍥涖丣DOM涓昏浣跨敤鏂規硶
1.Ducument綾?/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"));
榪欑偣鍜孌OM涓嶅悓銆侱om鍒欓渶瑕佹洿涓哄鏉傜殑浠g爜錛屽涓嬶細
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);
娉ㄦ剰浜嬮」錛欽DOM涓嶅厑璁稿悓涓涓妭鐐瑰悓鏃惰2涓垨澶氫釜鏂囨。鐩稿叧鑱旓紝瑕佸湪絎?涓枃妗d腑浣跨敤鍘熸潵鑰佹枃妗d腑鐨勮妭鐐圭殑璇濄傞鍏堥渶瑕佷嬌鐢╠etach()鎶婅繖涓妭鐐瑰垎寮鏉ャ?/p>
(2)浠庢枃浠躲佹祦銆佺郴緇烮D銆乁RL寰楀埌Document瀵硅薄錛?/p>
DOMBuilder builder = new DOMBuilder();
Document doc = builder.build(new File("jdom_test.xml"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(url);
鍦ㄦ柊鐗堟湰涓璂OMBuilder 宸茬粡Deprecated鎺?DOMBuilder.builder(url)錛岀敤SAX鏁堢巼浼氭瘮杈冨揩銆?/p>
榪欓噷涓句竴涓皬渚嬪瓙錛屼負浜嗙畝鍗曡搗瑙侊紝浣跨敤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鐨刣ocument鍜孞DOM鐨凞ocument涔嬮棿鐨勭浉浜掕漿鎹嬌鐢ㄦ柟娉曪紝綆鍗曪紒
DOMBuilder builder = new DOMBuilder();
org.jdom.Document jdomDocument = builder.build(domDocument);
DOMOutputter converter = new DOMOutputter();// work with the JDOM document…
org.w3c.dom.Document domDocument = converter.output(jdomDocument);
// work with the DOM document…
2.XML鏂囨。杈撳嚭
XMLOutPutter綾伙細
JDOM鐨勮緭鍑洪潪甯哥伒媧?鏀寔寰堝縐峣o鏍煎紡浠ュ強椋庢牸鐨勮緭鍑?/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 綾伙細
(1)嫻忚Element鏍?/p>
Element root = doc.getRootElement();//鑾峰緱鏍瑰厓绱爀lement
List allChildren = root.getChildren();// 鑾峰緱鎵鏈夊瓙鍏冪礌鐨勪竴涓猯ist
List namedChildren = root.getChildren("name");// 鑾峰緱鎸囧畾鍚嶇О瀛愬厓绱犵殑list
Element child = root.getChild("name");//鑾峰緱鎸囧畾鍚嶇О鐨勭涓涓瓙鍏冪礌
JDOM緇欎簡鎴戜滑寰堝寰堢伒媧葷殑浣跨敤鏂規硶鏉ョ鐞嗗瓙鍏冪礌錛堣繖閲岀殑List鏄痡ava.util.List錛?/p>
List allChildren = root.getChildren();
allChildren.remove(3); // 鍒犻櫎絎洓涓瓙鍏冪礌
allChildren.removeAll(root.getChildren("jack"));// 鍒犻櫎鍙?#8220;jack”鐨勫瓙鍏冪礌
root.removeChildren("jack"); // 渚挎嵎鍐欐硶
allChildren.add(new Element("jane"));// 鍔犲叆
root.addContent(new Element("jane")); // 渚挎嵎鍐欐硶
allChildren.add(0, new Element("first"));
(2)縐誨姩Elements:
鍦↗DOM閲屽緢綆鍗?/p>
Element movable = new Element("movable");
parent1.addContent(movable); // place
parent1.removeContent(movable); // remove
parent2.addContent(movable); // add
鍦―om閲?/p>
Element movable = doc1.createElement("movable");
parent1.appendChild(movable); // place
parent1.removeChild(movable); // remove
parent2.appendChild(movable); // 鍑洪敊!
琛ュ厖錛氱籂閿欐?/p>
JDOM鐨凟lement鏋勯犲嚱鏁幫紙浠ュ強瀹冪殑鍏朵粬鍑芥暟錛変細媯鏌lement鏄惁鍚堟硶銆?/p>
鑰屽畠鐨刟dd/remove鏂規硶浼氭鏌ユ爲緇撴瀯錛屾鏌ュ唴瀹瑰涓嬶細
1.鍦ㄤ換浣曟爲涓槸鍚︽湁鍥炵幆鑺傜偣
2.鏄惁鍙湁涓涓牴鑺傜偣
3.鏄惁鏈変竴鑷寸殑鍛藉悕絀洪棿錛圢amespaces錛?
(3)Element鐨則ext鍐呭璇誨彇
<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.鍙紜В閲婄壒孌婂瓧絎?/p>
element.setText("<xml> content");
4.CDATA鐨勬暟鎹啓鍏ャ佽鍑?/p>
element.addContent(new CDATA("<xml> content"));
String noDifference = element.getText();
娣峰悎鍐呭
element鍙兘鍖呭惈寰堝縐嶅唴瀹癸紝姣斿璇?/p>
<table>
<!-- Some comment -->
Some text
<tr>Some child element</tr>
</table>
鍙杢able鐨勫瓙鍏冪礌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) {...}
// 榪欓噷鍙互鍐欐垚Comment, Element, Text, CDATA,ProcessingInstruction, 鎴栬呮槸EntityRef鐨勭被鍨?/p>
}
// 鐜板湪縐婚櫎Comment,娉ㄦ剰榪欓噷娓告爣搴斾負1銆傝繖鏄敱浜庡洖杞﹂敭涔熻瑙f瀽鎴怲ext綾葷殑緙樻晠,鎵浠omment欏瑰簲涓?銆?/p>
mixedCo.remove(1);
4.Attribute綾?/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.澶勭悊鎸囦護(Processing Instructions)鎿嶄綔
涓涓狿ls鐨勪緥瀛?/p>
<?br?>
<?cocoon-process type="xslt"?>
| |
| |
鐩爣 鏁版嵁
澶勭悊鐩爣鍚嶇О(Target)
String target = pi.getTarget();
鑾峰緱鎵鏈夋暟鎹紙data錛夛紝鍦ㄧ洰鏍囷紙target錛変互鍚庣殑鎵鏈夋暟鎹兘浼氳榪斿洖銆?/p>
String data = pi.getData();
String type = pi.getValue("type");鑾峰緱鎸囧畾灞炴х殑鏁版嵁
List ls = pi.getNames();鑾峰緱鎵鏈夊睘鎬х殑鍚嶇О
6.鍛藉悕絀洪棿鎿嶄綔
<xhtml:html
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:title>Home Page</xhtml:title>
</xhtml:html>
Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");
List kids = html.getChildren("title", xhtml);
Element kid = html.getChild("title", xhtml);
kid.addContent(new Element("table", xhtml));
7.XSLT鏍煎紡杞崲
浣跨敤浠ヤ笅鍑芥暟鍙XSLT杞崲
鏈鍚庡鏋滀綘闇瑕佷嬌鐢╳3c鐨凞ocument鍒欓渶瑕佽漿鎹竴涓嬨?/p>
public static Document transform(String stylesheet錛孌ocument 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銆佺敓鎴恱ml鏂囨。錛?/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"); //鐢熸垚鍏冪礌錛歴tudent(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鏂囦歡鐨勫瓧絎︿負gb2312
format.setIndent(" "); //璁劇疆xml鏂囦歡鐨勭緝榪涗負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!");
}
}
鐢熸垚鐨剎ml鏂囨。涓猴細
<?xml version="1.0" encoding="gb2312"?>
<student-info>
<student>
<number>001</number>
<name>lnman</name>
<age>24</age>
</student>
</student-info>
鍒涘緩XML鏂囨。2錛?/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("http://www.bromon.org" );
Namespace ns2 = Namespace.getNamespace("other", "http://www.w3c.org" );
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("絎簩涓厓绱?);
el1.addContent(text1);
el1.addContent(em);
Element el2 = new Element("鍏冪礌涓?).addContent("絎笁涓厓绱?);
root.addContent(el1);
root.addContent(el2);
//緙╄繘鍥涗釜絀烘牸,鑷姩鎹㈣,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銆佽鍙杧ml鏂囨。鐨勪緥瀛愶細
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銆丏TD楠岃瘉鐨勶細
public class XMLWithDTD {
public void validate() {
try {
SAXBuilder builder = new SAXBuilder(true);
builder.setFeature("http://xml.org/sax/features/validation";,true);
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();
}
}
銆銆闇瑕佽鏄庣殑鏄紝榪欎釜紼嬪簭娌℃湁鎸囨槑浣跨敤鍝釜DTD鏂囦歡銆侱TD鏂囦歡鐨勪綅緗槸鍦╔ML涓寚瀹氱殑錛岃? 涓擠TD涓嶆敮鎸佸懡鍚嶇┖闂達紝涓涓猉ML鍙兘寮曠敤涓涓狣TD錛屾墍浠ョ▼搴忕洿鎺ヨ鍙朮ML涓寚瀹氱殑DTD錛岀▼搴忔湰韜笉鐢ㄦ寚瀹氥備笉榪囪繖鏍蜂竴鏉ワ紝濂借薄灝卞彧鑳戒嬌鐢ㄥ閮ㄥ紡 鐨凞TD寮曠敤鏂瑰紡浜嗭紵楂樹漢鎸囩偣銆?/p>
4銆乆ML Schema楠岃瘉鐨勶細
public class XMLWithSchema {
String xml="test.xml";
String schema="test-schema.xml";
public void validate() {
try {
SAXBuilder builder = new SAXBuilder(true);
//鎸囧畾綰︽潫鏂瑰紡涓篨ML schema
builder.setFeature("http://apache.org/xml/features/validation/schema";, true);
//瀵煎叆schema鏂囦歡
builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";,schema);
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("楠岃瘉澶辮觸:"+e);
}
}
}
涓婇潰鐨勭▼搴忓氨鎸囧嚭浜嗚寮曞叆鐨刋ML Schema鏂囦歡鐨勪綅緗?/p>
緋葷粺榛樿杈撳嚭鏄疷TF-8錛岃繖鏈夊彲鑳藉鑷村嚭鐜頒貢鐮併?/p>
5銆乆path渚嬪瓙錛?/p>
JDOM鐨勫叧浜嶺PATH鐨刟pi鍦╫rg.jdom.xpath榪欎釜鍖呴噷銆傝繖涓寘涓嬶紝鏈変竴涓娊璞$被 XPath.java鍜屽疄鐜扮被JaxenXPath.java錛?浣跨敤鏃跺厛鐢╔Path綾葷殑闈欐佹柟娉昻ewInstance(String xpath)寰楀埌XPath瀵硅薄錛岀劧鍚庤皟鐢ㄥ畠鐨剆electNodes(Object context)鏂規硶鎴杝electSingleNode(Object context)鏂規硶錛屽墠鑰呮牴鎹畑path璇彞榪斿洖涓緇勮妭鐐?List瀵硅薄)錛涘悗鑰呮牴鎹竴涓獂path璇彞榪斿洖絎﹀悎鏉′歡鐨勭涓涓妭鐐?Object綾? 鍨?銆傝鐪媕dom-1.0鑷甫鐨勮寖渚嬬▼搴忥細
瀹冨垎鏋愬湪web.xml鏂囦歡涓殑娉ㄥ唽鐨剆ervlet鐨勪釜鏁板強鍙傛暟涓暟錛屽茍杈撳嚭瑙掕壊鍚嶃?
web.xml鏂囦歡錛?
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
-->
<web-app>
<servlet>
<servlet-name>snoop</servlet-name>
<servlet-class>SnoopServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>file </servlet-name>
<servlet-class>ViewFile</servlet-class>
<init-param>
<param-name>initial</param-name>
<param-value>1000</param-value>
<description>The initial value for the counter <!-- optional --></description>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mv</servlet-name>
<url-pattern>*.wm</url-pattern>
</servlet-mapping>
<distributed/>
<security-role>
<role-name>manager</role-name>
<role-name>director</role-name>
<role-name>president</role-name>
</security-role>
</web-app>
澶勭悊紼嬪簭錛?
import java.io.*;
import java.util.*;
public class XPathReader {
public static void main(String[] args) throws IOException, JDOMException {
if (args.length != 1) {
System.err.println("Usage: java XPathReader web.xml");
return;
}
String filename = args[0];//浠庡懡浠よ杈撳叆web.xml
PrintStream out = System.out;
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));//寰楀埌Document瀵硅薄
// Print servlet information
XPath servletPath = XPath.newInstance("http://servlet");//,閫夋嫨浠繪剰璺緞涓媠ervlet鍏冪礌
List servlets = servletPath.selectNodes(doc);//榪斿洖鎵鏈夌殑servlet鍏冪礌銆?/p>
out.println("This WAR has "+ servlets.size() +" registered servlets:");
Iterator i = servlets.iterator();
while (i.hasNext()) {//杈撳嚭servlet淇℃伅
Element servlet = (Element) i.next();
out.print("\t" + servlet.getChild("servlet-name")
.getTextTrim() +
" for " + servlet.getChild("servlet-class")
.getTextTrim());
List initParams = servlet.getChildren("init-param");
out.println(" (it has " + initParams.size() + " init params)");
}
// Print security role information
XPath rolePath = XPath.newInstance("http://security-role/role-name/text()");
List roleNames = rolePath.selectNodes(doc);//寰楀埌鎵鏈夌殑瑙掕壊鍚?
if (roleNames.size() == 0) {
out.println("This WAR contains no roles");
} else {
out.println("This WAR contains " + roleNames.size() + " roles:");
i = roleNames.iterator();
while (i.hasNext()) {//杈撳嚭瑙掕壊鍚?
out.println("\t" + ((Text)i.next()).getTextTrim());
}
}
}
}
杈撳嚭緇撴灉:
C:\java>java XPathReader web.xml
This WAR has 2 registered servlets:
snoop for SnoopServlet (it has 0 init params)
file for ViewFile (it has 1 init params)
This WAR contains 3 roles:
manager
director
president
6銆佹暟鎹緭鍏ヨ鐢ㄥ埌XML鏂囨。瑕侀氳繃org.jdom.input鍖咃紝鍙嶈繃鏉ラ渶瑕乷rg.jdom.output銆傚鍓嶉潰鎵璇達紝鍏蟲槸鐪婣PI鏂囨。灝辮兘澶熶嬌鐢ㄣ?
鎴戜滑鐨勪緥瀛愯鍏ML鏂囦歡exampleA.xml錛屽姞鍏ヤ竴鏉″鐞嗘寚浠わ紝淇敼絎竴鏈功鐨勪環鏍煎拰浣滆咃紝騫舵坊鍔犱竴鏉″睘鎬э紝鐒跺悗鍐欏叆鏂囦歡exampleB.xml錛?
//exampleA.xml
<?xml version="1.0" encoding="GBK"?>
<bookList>
<book>
<name>Java緙栫▼鍏ラ棬</name>
<author>寮犱笁</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML鍦↗ava涓殑搴旂敤</name>
<author>鏉庡洓</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList>
//testJDOM.java
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*;
public class TestJDOM{
public static void main(String args[])throws Exception{
SAXBuilder sb = new SAXBuilder();
//浠庢枃浠舵瀯閫犱竴涓狣ocument錛屽洜涓篨ML鏂囦歡涓凡緇忔寚瀹氫簡緙栫爜錛屾墍浠ヨ繖閲屼笉蹇呬簡
Document doc = sb.build(new FileInputStream("exampleA.xml"));
ProcessingInstruction pi = new ProcessingInstruction//鍔犲叆涓鏉″鐞嗘寚浠?
("xml-stylesheet","href=\"bookList.html.xsl\" type=\"text/xsl\"");
doc.addContent(pi);
Element root = doc.getRootElement(); //寰楀埌鏍瑰厓绱?
java.util.List books = root.getChildren(); //寰楀埌鏍瑰厓绱犳墍鏈夊瓙鍏冪礌鐨勯泦鍚?
Element book = (Element)books.get(0); //寰楀埌絎竴涓猙ook鍏冪礌
//涓虹涓鏈功娣誨姞涓鏉″睘鎬?
Attribute a = new Attribute("hot","true");
book.setAttribute(a);
Element author = book.getChild("author"); //寰楀埌鎸囧畾鐨勫瓧鍏冪礌
author.setText("鐜嬩簲"); //灝嗕綔鑰呮敼涓虹帇浜?
//鎴?Text t = new Text("鐜嬩簲");book.addContent(t);
Element price = book.getChild("price"); //寰楀埌鎸囧畾鐨勫瓧鍏冪礌
//淇敼浠鋒牸錛屾瘮杈冮儊闂風殑鏄垜浠繀欏昏嚜宸辮漿鎹㈡暟鎹被鍨嬶紝鑰岃繖姝f槸JAXB鐨勪紭鍔?
author.setText(Float.toString(50.0f));
String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");
outp.output(doc, new FileOutputStream("exampleB.xml"));
}
};
鎵ц緇撴灉exampleB.xml錛?
<?xml version="1.0" encoding="GBK"?>
<bookList>
<book hot=”true”>
<name>Java緙栫▼鍏ラ棬</name>
<author>50.0</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML鍦↗ava涓殑搴旂敤</name>
<author>鏉庡洓</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList>
<?xml-stylesheet href="bookList.html.xsl" type="text/xsl"?>
鍦ㄩ粯璁ゆ儏鍐典笅錛孞DOM鐨凟lement綾葷殑getText()榪欑被鐨勬柟娉曚笉浼氳繃婊ょ┖鐧藉瓧絎︼紝濡傛灉浣犻渶瑕佽繃婊わ紝鐢╯etTextTrim() 銆?/p>