SAX parses complex xml strings and saxxml strings
Simple xml can be parsed by converting to a javaBean. However, xml is usually nested at one layer during development. It is obvious that it cannot be parsed when it is converted to a javaBean. Here we introduce the Sax parsing.
First, we need jdom. jar. If you don't have any friends, download http://www.jdom.org/news/index.html.
Let's just look at the example.
Import java. io. IOException;
Import java. io. StringReader;
Import java. util. List;
Import org. jdom. Attribute;
Import org. jdom. Document;
Import org. jdom. Element;
Import org. jdom. JDOMException;
Import org. jdom. input. SAXBuilder;
Import org. xml. sax. InputSource;
Public class SaxmlStrDemo {
Public static void main (String [] args ){
String xml = "<? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> "+
"<Submittask tasktypename = \" kind1 \ "perfrenceNum = \" 2 \ ">" +
"<Input name = \" Zhang San \ "value = \" 23 \ "inputindex = \" 1 \ "perfrence = \" 2 \ ">" +
"<Input1> Li Si </input1>" +
"</Input>" + "</submittask> ";
SaxXml (xml );
}
Private static void SaxXml (String xml ){
Try {
// Convert an xml string to a readable string
StringReader reader = new StringReader (xml );
// Create an Input Source
InputSource source = new InputSource (reader );
// Sax Parser
SAXBuilder sb = new SAXBuilder ();
// Construct a document object through the Input Source
Document doc = sb. build (source );
// Obtain the root node
Element root = doc. getRootElement ();
String name = root. getName ();
System. out. println ("root node attribute name:" + name); // output submittask
/**
* Development is the most common place. Generally, xml nodes carry attributes and node values --*****
*/
Attribute attribute Attribute = root. getAttribute ("tasktypename ");
System. out. println (attribute. getValue (); // output kind1
// Obtain the specified subnode under the root node
Element rootChild = root. getChild ("input ");
System. out. println (rootChild. getName ());
// You can also obtain the specified subnode using the following methods:
Element eRootChild = null;
List childrenList = root. getChildren ();
For (int I = 0; I <childrenList. size (); I ++ ){
ERootChild = (Element) childrenList. get (I );
System. out. println (eRootChild. getName ());
}
// We have obtained the input node rootChild under the root node. We can continue to obtain its child node. Here we obtain
Element inputChild = rootChild. getChild ("input1 ");
String input1_Name = inputChild. getName ();
String input0000value = inputChild. getValue ();
System. out. println (input1_Name + "====" + input1_Value); // input1 ==== Li Si
} Catch (JDOMException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}