Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the white spaces between tags in XML

Tags:

android

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.

like image 488
Miya Avatar asked Nov 25 '10 07:11

Miya


1 Answers

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

As an example:

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

Would remove all whitespace between every XML element.

like image 92
Knossos Avatar answered Oct 01 '22 19:10

Knossos