This article introduces how to quickly construct an XML fragment when programming in Java, and then output the XML.
XML is often used when developing in daily Java. XML is easy to use, but annoying to write. Is there a simple construction and output method? And look down.
1. Import jar package and namespace
To use XML in Java, it is recommended to import a jar package-dom4j first. This is a jar package specially designed for processing XML, which is very easy to use.
Then import the following three classes:
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element;
2. Define the XML schema
Before writing anything in the XML fragment, you must first create an XML fragment, or in other words XML Document. In the following program, a Document object is first created, and then a root element (Element) is created on it.
Document document = DocumentHelper.createDocument(); Element root = document.addElement("return");
3. Add child nodes
After you have the root node element, you can add child nodes to it.
Element returnvalue = root.addElement("returnvalue"); Element returninfo = root.addElement("returninfo");
4. Add content to child nodes
You can add content to already created child nodes:
returnvalue.addText("false"); returninfo.addText("get-session-fail");
You can also add content while creating child nodes:
root.addElement("id").addText("12345");
Note that when using addText to add node text content, sometimes we will directly use variables as parameters of the function. If this variable is null, the addText function will report an error. If it is other non-string type, an error will also be reported. You can add an empty string after the parameter to avoid errors.
is as follows:
int id=1; root.addElement("id").addText(id+"");
5. Output XML
If you just want to get the XML string, then the following sentence will do it.
String output = document.asXML();
If you want to use this XML as the output of the entire web page, then you must:
response.setContentType("text/xml"); response.write(output);
This article only introduces so much about the construction and output of XML in Java. I hope it will be helpful to you. ,Thanks!
For more articles related to the concise tutorial on constructing and generating XML in Java, please pay attention to the PHP Chinese website!