1

I'm trying to find a Java sub-string and then delete it without deleting the rest of the string.

I am taking XML as input and would like to delete a deprecated tag, so for instance:

public class whatever {
    public static void main(String[] args) {

    String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
    CharSequence deleteRaise = "<name>";

    // If an Addenda exists we continue with the process    
    if (xml_in.contains(deleteRaise)){
        // delete
    } else {
        // Carry on
    }
}

In there I would like to delete the <name> and </name> tags if they are included in the string while leaving <someStuff> and </someStuff>.

I already parsed the XML to a String so there's no problem there. I need to know how to find the specific strings and delete them.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Erick
  • 2,488
  • 6
  • 29
  • 43
  • 2
    Try `replace` method in `String` class. – yskkin May 07 '14 at 00:49
  • Submit it as an answer please, that was pretty much all I needed. So I'd like to give the valid answer. – Erick May 07 '14 at 00:52
  • What do you mean, "parsed XML to a String"? Also, any reason you don't use an XML parser for XML manipulation, such as Xerces? Manipulating XML by regexp is... [dangerous](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – Amadan May 07 '14 at 00:53
  • Filtering of the XML will be more efficient if it is done prior to converting the XML to a string. With XSLT it is possible to filter out all the `` tags and make other alternations as needed. – Jason Aller May 07 '14 at 00:57

2 Answers2

3

You can use replaceAll(regex, str) to do this. If you're not familiar with regex, the ? just means there can be 0 or 1 occurrences of / in the string, so it covers <name> and </name>

String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String filter = "</?name>";
uploadedXML = uploadedXML.replaceAll(filter, "");

System.out.println(uploadedXML);

 <someStuff>Bats!</someStuff>
Mdev
  • 2,440
  • 2
  • 17
  • 25
1
String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String deleteRaise = "<name>";
String closeName = "</name>"
// If an Addenda exists we continue with the process    
if (xml_in.contains(deleteRaise)){
    uploadedXML.replace(uploadedXML.substring(uploadedXML.indexOf(deleteRaise),uploadedXML.indexOf(closeName)+1),"");
} else {
    // Carry on
}enter code here
TheTechWolf
  • 2,084
  • 2
  • 19
  • 24