0

I have the following XML stored in a String

<MessageHeader>
<MessageThreadId>201401140942060</MessageThreadId>
</MessageHeader>
<MessageNotificationPeriod>
<StartDate>2013-11-01T00:00:00.000000</StartDate>
<EndDate>2013-12-01T00:00:00.000000</EndDate>
</MessageNotificationPeriod>
<SalesReport>
<SalesByTerritory>
<TerritoryCode>US</TerritoryCode>
</SalesByTerritory>
</SalesByCommercialModel>
</SalesReport>

I want to split the string into 3 parts so that it can be printed at different places in the file I will be creating. I want </MessageNotificationPeriod> to end the first part, </TerritoryCode> to end the second part and the remaining to be in the third new string. I've tried to use String.split() but it removes the string I am splitting at.

user1712258
  • 117
  • 3
  • 7
  • 5
    You should consider to use an XML Parser instead of string splitting, check http://stackoverflow.com/questions/373833/best-xml-parser-for-java – krampstudio Jan 24 '14 at 11:22
  • There's technical reasons for creating the file in this way based on how the data(SalesByTerritory) is coming from the database. – user1712258 Jan 24 '14 at 11:23

2 Answers2

1

If you don't want to parse the XML, it's easy enough to use a regex:

Pattern pattern = Pattern.compile(
    "^(.*</MessageNotificationPeriod>)(.*</TerritoryCode>)(.*)$"
);
Matcher matcher = pattern.matcher(xmlString);
if (!matcher.matches()) { 
   throw new IllegalStateException();
}
String part1 = matcher.group(1);
String part2 = matcher.group(2);
String part3 = matcher.group(3);

See the capturing groups tutorial

lance-java
  • 25,497
  • 4
  • 59
  • 101
-1

did you try subString(start, end) method

user3041570
  • 21
  • 1
  • 4