Import org.jdom.Document;
Import org.jdom.Element;
Import org.jdom.JDOMException;
Import Org.jdom.Namespace;
Import Org.jdom.input.SAXBuilder;
Import Org.xml.sax.InputSource;
public class Duxmldoc {
Public List xmlelements (String xmldoc) {
Create a new string
StringReader read = new StringReader (xmldoc);
Creating a new input source The SAX parser uses the InputSource object to determine how to read the XML input
InputSource Source = new InputSource (read);
Create a new Saxbuilder
Saxbuilder sb = new Saxbuilder ();
try {
Constructs a document from the input source
Document doc = sb.build (source);
The root element taken
Element root = Doc.getrootelement ();
System.out.println (Root.getname ());//The name of the output root element (test)
Gets the collection of all child elements of the root element
List Jiedian = Root.getchildren ();
Get namespaces in XML (undefined in XML is not writable)
Namespace ns = Root.getnamespace ();
Element et = null;
for (int i=0;i<jiedian.size (); i++) {
ET = (Element) jiedian.get (i);//loop to get child elements sequentially
/**//*
* When no namespace is defined
* Et.getchild ("users_id"). GetText ();
* Et.getchild ("users_address", NS). GetText ()
*/
System.out.println (Et.getchild ("users_id", NS). GetText ());
System.out.println (Et.getchild ("users_address", NS). GetText ());
}
/**//*
* If you want to take the name of the child element under <row>
*/
ET = (Element) jiedian.get (0);
List Zjiedian = Et.getchildren ();
for (int j=0;j<zjiedian.size (); j + +) {
Element Xet = (Element) Zjiedian.get (j);
System.out.println (Xet.getname ());
}
} catch (Jdomexception e) {
TODO automatically generates catch blocks
E.printstacktrace ();
} catch (IOException e) {
TODO automatically generates catch blocks
E.printstacktrace ();
}
return null;
}
public static void Main (string[] args) {
Duxmldoc doc = new Duxmldoc ();
String xml = "<?xml version=\" 1.0\ "encoding=\" gb2312\ "?>" +
"<result xmlns=\" http://www.fiorano.com/fesb/activity/dbqueryoninput2/out\ ">" +
"<row resultcount=\" 1\ ">" +
"<users_id>1001 </users_id>" +
"<users_name>wangwei </users_name>" +
"<users_group>80 </users_group>" +
"<users_address>1001 </users_address>" +
"</row>" +
"<row resultcount=\" 1\ ">" +
"<users_id>1002 </users_id>" +
"<users_name>wangwei </users_name>" +
"<users_group>80 </users_group>" +
"<users_address>1002 </users_address>" +
"</row>" +
"</Result>";
Doc.xmlelements (XML);
}
}
Parsing of XML strings