public void test() throws ParserConfigurationException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlStandalone(true); //无效
Element request = doc.createElement("request");
Element sn = doc.createElement("sn");
Element user = doc.createElement("user");
Element passwd = doc.createElement("passwd");
Element args = doc.createElement("args");
Element arg1 = doc.createElement("arg");
arg1.setAttribute("name", "arg1");
Element arg2 = doc.createElement("arg");
arg2.setAttribute("name", "arg2");
Element arg3 = doc.createElement("arg");
arg3.setAttribute("name", "arg3");
sn.setTextContent("201601011234567890");
user.setTextContent("XXXX");
passwd.setTextContent("XXXX");
arg1.setTextContent("Y");
arg2.setTextContent("YY");
arg3.setTextContent("YYY");
doc.appendChild(request);
request.appendChild(sn);
request.appendChild(user);
request.appendChild(passwd);
request.appendChild(args);
args.appendChild(arg1);
args.appendChild(arg2);
args.appendChild(arg3);
System.out.println(XmlTools.docToStr(doc, true));
}
输出结果
201601011234567890
XXXX
XXXX
Y
YY
YYY
我是想要standalone="yes"的,但是用doc.setXmlStandalone(true)方法行不通