Reputation: 42967
I have something like:
String idCodice = cessionarioCommittente.substring(
cessionarioCommittente.indexOf("<IdCodice>") + 10,
cessionarioCommittente.indexOf("</IdCodice>"));
used to extract the value inside the tag of an XML document represented by the content of the cessionarioCommittente
String variable.
The problem is that the <IdCodice>
tag might not exist in the cessionarioCommittente
String.
So in this case I get this exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -10
at java.lang.String.substring(String.java:1937)
at it.sistinf.ediwea.fepa.LoadFatturePa.run(LoadFatturePa.java:103)
at it.sistinf.ediwea.fepa.TestLoadFatturePa.main(TestLoadFatturePa.java:18)
How can I fix this issue? For example, checking if this value exists in the string?
Upvotes: 1
Views: 916
Reputation: 31
String.indexOf() returns -1 if the string was not found. Check if the return value is >= 0 before doing something with it.
Upvotes: 2
Reputation: 1496
before doing the sub string you can use something like:
String idCodice;
if(cessionarioCommittente.indexOf("<IdCodice>") > -1){
idCodice = cessionarioCommittente.substring(cessionarioCommittente.indexOf("<IdCodice>") + 10, cessionarioCommittente.indexOf("</IdCodice>"));
}
Be careful of performance issues when searching in the string either using indexOf or contains (note: contains() method internally uses indexOf()). but my question is, why are you parsing xml manually, there are many libraries doing so efficiently. here! is a very simple example
Upvotes: 0
Reputation: 13465
You can do as suggested by Eran or you can use the contains
method and the ternary operator:
idCodice = (cessionarioCommittente.contains("<IdCodice>") &&cessionarioCommittente.contains("</IdCodice>")) ? cessionarioCommittente.substring(cessionarioCommittente.indexOf("<IdCodice>") + 10, cessionarioCommittente.indexOf("</IdCodice>")):null;
Upvotes: 1
Reputation: 393846
You can do a preliminary check to make sure the tags you are looking for are present in the String :
String idCodice = null;
int startTag = cessionarioCommittente.indexOf("<IdCodice>");
int endTag = cessionarioCommittente.indexOf("</IdCodice>");
if (startTag >= 0 && endTag > startTag) {
idCodice = cessionarioCommittente.substring(startTag + 10, endTag);
}
By storing the indices in variables you avoid searching for them twice.
Upvotes: 4