1 9 10 package org.dom4j.samples.rule; 11 12 import java.net.URL ; 13 14 import org.dom4j.Document; 15 import org.dom4j.DocumentHelper; 16 import org.dom4j.Element; 17 import org.dom4j.Node; 18 import org.dom4j.io.OutputFormat; 19 import org.dom4j.io.SAXReader; 20 import org.dom4j.io.XMLWriter; 21 import org.dom4j.rule.Action; 22 import org.dom4j.rule.Rule; 23 import org.dom4j.rule.Stylesheet; 24 25 39 public class SongFilter { 40 41 private Document resultDoc; 42 43 private Element songElement; 44 45 private Element currentSongElement; 46 47 private Stylesheet style; 48 49 50 public SongFilter() { 51 this.songElement = DocumentHelper.createElement("song"); 52 } 53 54 public Document filtering(org.dom4j.Document doc) throws Exception { 55 Element resultRoot = DocumentHelper.createElement("result"); 56 this.resultDoc = DocumentHelper.createDocument(resultRoot); 57 58 Rule songElementRule = new Rule(); 59 songElementRule.setPattern(DocumentHelper 60 .createPattern("/Songs/song/mp3/id3")); 61 songElementRule.setAction(new SongElementBuilder()); 62 63 Rule titleTextNodeFilter = new Rule(); 64 titleTextNodeFilter.setPattern(DocumentHelper 65 .createPattern("/Songs/song/mp3/id3/title")); 66 titleTextNodeFilter.setAction(new NodeTextFilter()); 67 68 this.style = new Stylesheet(); 69 this.style.addRule(songElementRule); 70 this.style.addRule(titleTextNodeFilter); 71 72 style.run(doc); 73 74 return this.resultDoc; 75 } 76 77 private class SongElementBuilder implements Action { 78 public void run(Node node) throws Exception { 79 currentSongElement = songElement.createCopy(); 80 resultDoc.getRootElement().add(currentSongElement); 81 82 style.applyTemplates(node); 83 } 84 } 85 86 private class NodeTextFilter implements Action { 87 public void run(Node node) throws Exception { 88 if (currentSongElement != null) { 89 currentSongElement.setText(node.getText()); 90 } 91 } 92 } 93 94 public static void main(String [] args) throws Exception { 95 SongFilter filter = new SongFilter(); 96 URL source = filter.getClass().getResource( 97 "/org/dom4j/samples/rule/Songs.xml"); 98 Document result = filter.filtering(new SAXReader().read(source)); 99 100 XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); 101 writer.setOutputStream(System.out); 102 writer.write(result); 103 104 } 105 106 } 107 108 146 | Popular Tags |