This article introduces how to quickly construct an XML fragment when programming in Java, and then output the XML.
XML is often used in daily Java development. XML is easy to use, but annoying to write. Is there a simple construction and output method? And look down.
1. Import the jar package and namespace
To use XML in Java, it is recommended to first import a jar package-dom4j. This is a jar package specially designed for processing XML, which is very easy to use.
Then import the following three classes:
Copy the code code as follows:
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
2. Define XML schema
Before writing something into an XML fragment, you must first create an XML fragment, or XML Document. In the following program, a Document object is first created, and then a root element (Element) is created on it.
Copy the code code as follows:
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.
Copy the code code as follows:
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:
Copy the code code as follows:
returnvalue.addText("false");
returninfo.addText("get-session-fail");
You can also create child nodes and add content at the same time:
Copy the code code as follows:
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.
as follows:
Copy the code code 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.
Copy the code as follows: String output = document.asXML();
If you want to use this XML as the output of the entire web page, then you need to:
Copy the code as follows: response.setContentType("text/xml");
response.write(output);
Regarding the construction and output of XML in Java, this article has introduced so much. I hope it will be helpful to you, thank you!