67,538
社区成员
发帖
与我相关
我的任务
分享
/**
* 创建xml
*
* @param method
* 要访问的方法(webservice专用)
* @param path
* xml路径
* @param elements
* 子元素
*/
static public Document createXML(Element method, String path,
Element... elements)
{
// declare root element
Element root = new Element("Envelope");
// declare header element
Element header = new Element("Header");
// declare body element
Element body = new Element("Body");
// declare three namespaces
// first param is prefixs,second param is uri
Namespace soap = Namespace.getNamespace("soap",
"http://schemas.xmlsoap.org/soap/envelope/");
Namespace xsd = Namespace.getNamespace("xsd",
"http://www.w3.org/2001/XMLSchema");
Namespace xsi = Namespace.getNamespace("xsi",
"http://www.w3.org/2001/XMLSchema-instance");
// put namespace to root element
root.addNamespaceDeclaration(soap);
root.addNamespaceDeclaration(xsd);
root.addNamespaceDeclaration(xsi);
// put header element to root element
root.addContent(header);
// put body element to root element
root.addContent(body);
// with root set namespace prefixs
root.setNamespace(soap);
// with header set namespace prefix
header.setNamespace(soap);
// with body element set namespace prefixs
body.setNamespace(soap);
body.addContent(method);
for (int i = 0; i < elements.length; ++i)
{
method.addContent(elements[i]);
}
// declare document element
Document doc = new Document(root);
// declare xml format class
Format format = Format.getPrettyFormat();
// set encoding for xml
format.setEncoding("UTF-8");
// set indent for xml
format.setIndent(" ");
// set expaned empty elements for xml
format.setExpandEmptyElements(true);
// xml file output class
XMLOutputter outputter = new XMLOutputter(format);
// output
try
{
outputter.output(doc, new FileWriter(path));
} catch (IOException e)
{
e.printStackTrace();
System.out.println("File path is not correct!" + e.getMessage());
}
return doc;
}