简体   繁体   中英

How to extract a value from a string

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>

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);
}
}

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM