Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

android - How to remove the white spaces between tags in XML

I created an XML document using Java in my android application. I have to call a web service in my application and pass this XML as an argument there. But my problem is there created a white space between each tag in the 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();

The XML is:

<subscriber> <UserName>miya</UserName> <Password>today</Password> </subscriber>

Please give the solution for how to remove the white spaces between the UserName and Password tags.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Of course, it depends on your XML itself. However, you could try using regular expressions.

As an example:

yourXmlAsString.replaceAll(">[\s
]*<", "><");

Would remove all whitespace between every XML element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...