-1

I need one help regarding my xml . I want to remove space between the element name of xml tags . for eg : I have one xmlstring it consists of xml tags like <Customer name><address book > like this so i want to remove space between customer & name . it should look like <customername>&<addressbook>. Only spaces between xml tags element name. Please help on this using xslt or java.

5
  • 1
    It's not possible to have xml with a space in the element name like <Customer name>, since that is not valid XML. And because of that, you cannot read it using an XML parser, so you cannot fix it. Jun 14, 2016 at 5:09
  • Hi , yes I know actually what I did is using java code I am converting json string to xmlstring .But before parsing it using xmlparser I want to do the conversion then only it will parse as you mentioned .
    – T14h1r
    Jun 14, 2016 at 5:12
  • 1
    Fix it when you do the conversion from json to xml, not later. Jun 14, 2016 at 5:16
  • Hi Erwin , Thanks for your response . But actually I am converting using jar file org.json . So , its provide simple one method to convert it . So unable to do any change at the time of conversion .Could you please help me in this .
    – T14h1r
    Jun 14, 2016 at 5:21
  • No I would have to look that up with Google just like you. But you can raise a new question that focused on the json to xml conversion; you probably get a better response that way. Also look at existing questions tagged with org.json first: stackoverflow.com/questions/tagged/org.json Jun 14, 2016 at 5:38

1 Answer 1

0

If we match on patterns that contain white space in between two brackets < and > then we can take those groups and do a replace all of the white space and re-insert them into the original string.

String input = "<Customer name> <address book >";

Pattern p = Pattern.compile("(<[^>]*?\\s[^>]*?>)");
Matcher m = p.matcher(input);

StringBuffer result = new StringBuffer();

while (m.find()) {
    String replace = m.group().replaceAll("\\s+", "");
    m.appendReplacement(result, replace);
}

m.appendTail(result);
System.out.println(result);

This would print out . The pattern looks for a starting brace, matches on anything that isn't an ending brace until it finds white space, then matches on anything not an ending brace until it finds an ending brace. If we find a match, we remove the white space and replace the match back into the input string.

1
  • And if the source contains an attribute? Jun 14, 2016 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.