import java.util.*;import java.io.*;import org.jdom.*;import org.jdom.input.*;import org.jdom.output.*;public class ExampleJdomAttr{ public static void main( String[] args ) { if( args.length != 7 ) { System.err.println( "Attention:" ); System.err.println( "jdom.jar must be added to classpath." ); System.err.println( "Usage:" ); System.err.println( "java ExampleJdomAttr <XmlFile> <NewFile>" + " <Elem> <AttrS> <ValS> <AttrNew> <ValN>" ); System.err.println( "Example:" ); System.err.println( "java -classpath .;jdom.jar ExampleJdomAttr" + " MyXmlFile.xml NewXmlFile.xml" + " Button size small col blue" ); System.exit( 1 ); } try { // ---- Read XML file ---- SAXBuilder builder = new SAXBuilder(); Document doc = builder.build( new File( args[0] ) ); // ---- Modify XML data ---- Element root = doc.getRootElement(); List listMainElements = root.getChildren( args[2] ); // <MainElem> for( int i=0; i<listMainElements.size(); i++ ) { // Find searched element with given attribute: Element elMain = (Element)(listMainElements.get( i )); if( null == elMain ) continue; String s = elMain.getAttributeValue( args[3] ); // <AttrS> if( null == s || !s.equals( args[4] ) ) continue; // <ValS> // Add new attribute to correct element: elMain.setAttribute( args[5], args[6] ); // <AttrNew>=<ValN> // ---- Write result ---- XMLOutputter outp = new XMLOutputter(); outp.setIndent( " " ); outp.setNewlines( true ); // ---- Show the modified element on the screen ---- System.out.println( "\nModified Element:\n" ); outp.output( elMain, System.out ); System.out.println(); // ---- Write the complete result document to XML file ---- outp.output( doc, new FileOutputStream( new File( args[1] ) ) ); break; // <NewFile> } } catch( Exception ex ) { ex.printStackTrace(); } }}
.;E:\jdk1.5.0_05\lib\tools.jar;H:\programmierung\xml\jdom-1.0\build\jdom.jar;H:\programmierung\xml\xerces-2_7_1\xercesImpl.jar;H:\programmierung\xml\xerces-2_7_1\xercesSamples.jar;H:\programmierung\xml\xerces-2_7_1\xml-apis.jar;