1.选定文件,取名example1.xml,内容如下:
<root>
<foo>bar</foo>
<hugo xmlns="http://hugospace.org">
<hugochild>This is in a <!-- comment -->new namespace</hugochild>
</hugo>
<bar testattr='123abc' />
</root>
2.建立java类,如下:
import java.io.*;
import org.kxml2.kdom.*;
import org.kxml2.io.*;
import org.xmlpull.v1.*;
/**
* @author Stefan Haustein
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
*/
public class KdomTest {
/**
* Constructor for KDomRoundtrip.
*/
public static void main(String[] args) throws IOException, XmlPullParserException {
KdomTest kdom = new KdomTest();
System.out.println ("generating KDom from ");
KXmlParser parser = new KXmlParser ();
parser.setInput(new InputStreamReader(kdom.getClass().getResourceAsStream("example1.xml")));
parser.setFeature (XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
Document doc = new Document ();
doc.parse (parser);
Element rootElement = doc.getRootElement();
System.out.println("**********root name*************"+rootElement.getName()+"****child count:"+rootElement.getChildCount()+"***text:"+rootElement.getText(0));
Element child1 = (Element)rootElement.getChild(1);
System.out.println("child1***name"+child1.getName()+"***text:"+child1.getText(0));
Element child2 = (Element)rootElement.getChild(3);
System.out.println("child2***name"+child2.getName()+"**namespace:"+child2.getNamespace()+"**attribute count"+child2.getAttributeCount()+"**text:"+child2.getText(0));
KXmlSerializer serializer = new KXmlSerializer ();
serializer.setOutput (System.out, null);
doc.write (serializer);
serializer.flush ();
}
}