Question

I know how to do it "brutally" but I am wondering of a smart and short way to read xml parameters from a string:

x="0" y="0" width="30" height="64"

Do you have any ideas? I want to create a very small and fast method like:

int getValue(String string, String key)
Was it helpful?

Solution

If that is all there is in then string, then it is not XML.

In any case, assuming that there is a string that looks like that, consider a simple "brutal" regular expression capture (ideone) -

static String hackIt(String str, String key) {
  Pattern p = Pattern.compile("\\b" + Pattern.quote(key) + "=\"([^\"]*)\"");
  Matcher m = p.matcher(str);
  if (m.find()) {
      return m.group(1);
  } else {
      return null;
  }
}

Being not an XML parser it will fail to handle things like &quote; and allows pretty much any arbitrary (possible detrimental) value of key. Nested quotes will not work either, nor will spaces around the equal sign or .. but it does the requested task given a limited context and is likely Fast Enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top