我在我的 android 应用程序中使用 Java 创建了一个 XML 文档。我必须在我的应用程序中调用 Web 服务并将此 XML 作为参数传递到那里。但我的问题是在 XML 中的每个标记之间创建了一个空白。
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("subscriber");
doc.appendChild(root);
//creating child node for username
EditText txtusername=(EditText)findViewById(R.id.txtUserName);
subscriber[0]=String.valueOf(txtusername.getText());
Element UserName=doc.createElement("UserName");
UserName.setTextContent(subscriber[0]);
root.appendChild(UserName);
//creating child node for PASSWORD
EditText txtPassword=(EditText)findViewById(R.id.txtPassword);
subscriber[1]=String.valueOf(txtPassword.getText());
Element Password=doc.createElement("Password");
Password.setTextContent(subscriber[1]);
root.appendChild(Password);
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString =sw.toString();
url = new URL("http://192.168.70.14/NewsLetter/subscribing.php?register= " + xmlString);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "text/xml; charset=UTF-8");
dis = conn.getInputStream();
XML 是:
<subscriber> <UserName>miya</UserName> <Password>today</Password> </subscriber>
请给出如何去除UserName
和Password
标签之间的空格的解决方案。
最佳答案
当然,这取决于您的 XML 本身。但是,您可以尝试使用正则表达式。
举个例子:
yourXmlAsString.replaceAll(">[\\s\r\n]*<", "><");
将删除每个 XML 元素之间的所有空格。
关于android - 如何删除 XML 中标签之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4274524/