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.

4
  • 2
    Try replace method in String class. Commented May 7, 2014 at 0:49
  • Submit it as an answer please, that was pretty much all I needed. So I'd like to give the valid answer. Commented May 7, 2014 at 0: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. Commented May 7, 2014 at 0: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 <name> tags and make other alternations as needed. Commented May 7, 2014 at 0:57

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.