How to extract a value from a string

133 Views Asked by At

I have an variable which contains this value

<NewDataSet> <Table> <AirportCode>LKO</AirportCode> <CityOrAirportName>LUCKNOW AMAUSI</CityOrAirportName> <Country>India</Country> <CountryAbbrviation>IN</CountryAbbrviation> <CountryCode>733</CountryCode> <GMTOffset>-5.5</GMTOffset> <RunwayLengthFeet>7835</RunwayLengthFeet>

How can I extract the country code from this, in this case 733. Country code can be different, so I need to somehow get the value which is next to <CountryCode> and before </CountryCode>

3

There are 3 best solutions below

1
On

You should use Java DOM parser combined with Xpath. With that you can not only get country code but also other values from your xml like Airport code, CityAirportName etc. For examples of the code look at this site: https://www.tutorialspoint.com/java_xml/java_xpath_parse_document.htm

1
On

This looks like partial xml text because some closing tags are missing. If you have complete xml text then I would suggest you to use some xml parser like Dom parser for xml.

Otherwise you can do something like this

String countryCode = xmlText.substring("<CountryCode>".length() + xmlText.indexOf("<CountryCode>"),  xmlText.indexOf("</CountryCode>"));
System.out.println(countryCode);
0
On

Here you can Use easily JDOM,Xerces DOMParser or JAXP interfaces to parse your providing file is taking in a variable or you can save in XML file to read this file. and I think your providing file is not exactly in format like XML so I am providing you sub string method to find your desire results.

/**
*
* @author mahsin
* @date 27-12-2016
*/
public class Main{
public static void main(String args[]){
    String testText = "<NewDataSet> <Table> <AirportCode>LKO</AirportCode> <CityOrAirportName>LUCKNOW AMAUSI</CityOrAirportName> <Country>India</Country> <CountryAbbrviation>IN</CountryAbbrviation> <CountryCode>733</CountryCode> <GMTOffset>-5.5</GMTOffset> <RunwayLengthFeet>7835</RunwayLengthFeet>";
    String countryCode = testText.substring("<CountryCode>".length() + testText.indexOf("<CountryCode>"),  testText.indexOf("</CountryCode>"));
    System.out.println(countryCode);
}
}