This article mainly introduces the simple tutorial of constructing and generating XML in Java. This article is completed through the dom4j package. if you need it, refer to the following section to introduce how to program in Java, how to quickly construct an XML segment and then output it.
XML is often used for routine Java development. XML is easy to use, but it is annoying to write. Is there a very simple construction and output method? And look down.
1. import the jar package and namespace
To use XML in Java, we recommend that you first import a jar package -- dom4j. This is a jar package dedicated 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 architecture
Before writing something into an XML snippet, you must create an XML snippet, or an XML Document. In the following program, first create a Document object, and then create a root Element on it ).
Document document = DocumentHelper.createDocument();Element root = document.addElement("return");
3. add a subnode
With the root node element, you can add subnodes to it.
Element returnvalue = root.addElement("returnvalue");Element returninfo = root.addElement("returninfo");
4. add content for the subnode
You can add content to a created subnode:
returnvalue.addText("false");returninfo.addText("get-session-fail");
You can also add content when creating a subnode:
root.addElement("id").addText("12345");
Note: When addText is used to add node text content, sometimes variables are directly used as function parameters. If this variable is null, the addText function reports an error. If it is another non-string type, an error is returned. You can add an empty string after the parameter to avoid errors.
As follows:
int id=1;root.addElement("id").addText(id+"");
5. output XML
If you only want to get the XML string, you can do the following.
String output = document.asXML();
If you want to use this XML as the output of the entire webpage, you need:
response.setContentType("text/xml");response.write(output);
This article describes the construction and output of XML in Java. I hope it will help you. thank you!
For more articles about constructing and generating XML Concise Tutorials in Java, please follow the PHP Chinese network!