Jar Package to import: Jdom-2.0.6.jar
Package com.huawei.xml;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.List;
Import org.jdom2.Document;
Import org.jdom2.Element;
Import Org.jdom2.input.SAXBuilder;
Import Org.jdom2.output.Format;
Import Org.jdom2.output.XMLOutputter;
/**
*
* Jdom Analysis
* @author Administrator
*
*/
public class Testjdomparser {
public static void parser () throws exception{
Get the parser
Dombuilder is primarily used to build existing documents in memory
Saxbuilder is primarily used to build documents based on files or input streams
Saxbuilder builder = new Saxbuilder ();
InputStream in = TestJDOMParser.class.getClassLoader (). getResourceAsStream ("Com/cdsxt/resources/users.xml");
Document to be built
Document doc = Builder.build (in);
Get the root node first and then get the child elements.
Element root = Doc.getrootelement ();
Get all the son elements
List<element> childs = Root.getchildren ();
for (Element child:childs) {
System.out.println (Child.getattributevalue ("id"));
System.out.println (Child.getchildtext ("username"));
}
}
public static void Updatexml () {
}
/**
* Create an XML file
*/
public static void Createxml () throws exception{
All built Documents
Document doc = new document ();
element root = new Element ("Users");
Element user = new Element ("user");
User.setattribute ("id", "Zhanoliu"). SetAttribute ("name", "Test-user");
Element username = new Element ("username");
Username.addcontent ("Fengjie");
element email = new Element ("email");
Email.settext ("[email protected]");
Building relationships
User.setcontent (username);
User.setcontent (email);
Root.addcontent (user);
Doc.setrootelement (root);
Write out the built document
Create a file output
Xmloutputter outputter = new Xmloutputter ();
The default is no format, so to get a formatter to format the session code
Format format = Format.getprettyformat ();
Format.setindent ("");
Outputter.setformat (format);
Building the file output stream
OutputStream out = new FileOutputStream (New File ("F:/tttt.xml"));
Output file
Outputter.output (Doc, out);
Out.flush ();
Out.close ();
}
public static void Main (string[] args) throws Exception {
Parser ();
Createxml ();
}
}
Third-party tools Jdom Parsing xml