Java examples for java.lang:String XML
Find the integer value of an attribute starting at position k in a text string, returning the value of the attribute, or defaultValue if the attribute is not present.
/*--------------------------------------------------------------- * Copyright 2005 by the Radiological Society of North America * * This source software is released under the terms of the * RSNA Public License (http://mirc.rsna.org/rsnapubliclicense) *----------------------------------------------------------------*/ //package com.java2s; public class Main { /**//from w ww.j a v a 2s . c om * Find the integer value of an attribute starting at position k * in a text string, returning the value of the attribute, or * defaultValue if the attribute is not present. * @param text the XML string. * @param k the starting point in the XML string to search for the attribute. * @param attr the name of the attribute. * @param defaultValue the value to be returned if the attribute is not present * or if the conversion of the attribute value to an integer fails. * @return the integer value of the attribute, or the defaultValue. */ public static int getAttributeInt(String text, int k, String attr, int defaultValue) { int value = defaultValue; String attrValue = getAttribute(text, k, attr); if (attrValue != null) { try { value = Integer.parseInt(attrValue); } catch (Exception e) { } ; } return value; } /** * Find the string value of an attribute starting at position k in * a text string, returning the string value of the attribute, or * null if the attribute is not present. Note: this method returns * the value of the attribute with normalized whitespace. * @param text the XML string. * @param k the starting point in the XML string to search for the attribute. * @param attr the name of the attribute. * @return the string value of the attribute, or null if the attribute is not * present. */ public static String getAttribute(String text, int k, String attr) { int kk = text.indexOf(">", k); if (kk < 0) return null; String t = text.substring(k, kk).replaceAll("\\s+", " ") .replaceAll(" =", "=").replaceAll("= ", "="); k = t.indexOf(" " + attr + "="); if (k < 0) return null; k = t.indexOf("=", k) + 2; if (t.charAt(k - 1) != '"') return null; kk = t.indexOf("\"", k); if (kk < 0) return null; return t.substring(k, kk); } }