This article describes how to quickly construct an XML fragment in Java programming, and then output the XML.
XML is often used in the day-to-day use of Java development. XML is easy to use, but write annoying, there is no very simple construction and output methods? and look down.
1. Import jar Packages and namespaces
To use XML in Java, it is recommended that you pilot into a jar package--dom4j. This is a jar package that is designed to work with XML and is very useful.
Then import the following three classes:
Copy Code code as follows:
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
2. Defining XML Schemas
Before you write to an XML fragment, you create an XML fragment, or XML Document. In the following program, you create a Document object and then create a root element (element) above it.
Copy Code code as follows:
Document document = Documenthelper.createdocument ();
Element root = Document.addelement ("return");
3, add child nodes
Once you have the root node element, you can add the child nodes to it below.
Copy Code code as follows:
Element returnvalue = root.addelement ("returnvalue");
Element returninfo = root.addelement ("Returninfo");
4. Add content for child nodes
You can add content to child nodes that you have already created:
Copy Code code as follows:
Returnvalue.addtext ("false");
Returninfo.addtext ("Get-session-fail");
You can also add content while creating child nodes:
Copy Code code as follows:
Root.addelement ("id"). addtext ("12345");
Note that when you use AddText to add the content of the node text, sometimes we take the variables directly as arguments to the function. If this variable is null, the AddText function will give an error. If it is another type other than string, an error is also encountered. You can add an empty string after the argument to avoid the error.
As follows:
Copy Code code as follows:
int id=1;
Root.addelement ("id"). addtext (id+ "");
5. Output XML
If you just want to get the XML string, the following sentence is done.
Copy Code code as follows:
String output = Document.asxml ();
If you want to use this XML as the output of the entire Web page, you need to:
Copy Code code as follows:
Response.setcontenttype ("Text/xml");
Response.Write (output);
About the XML in Java construction and output, this article on the introduction of so many, I hope to help you, thank you!