How To Convert Java Regex To Extract Text Between Tags?

4.00K viewsJava
0

I have an XML file with some tags and I’d like to take exact tags data to form XML string between the tags.
For example, I need to take the name tag value.

<GetResponse>
<RuleInfo>
<Name>clarifyall</Name>
<DataType>RichTextFormat</DataType>
</RuleInfo>
</GetResponse>

Manohar Changed status to publish October 8, 2019
Add a Comment
3

Use below code .

private static final Pattern TAG_REGEX = Pattern.compile("<Name>(.+?)</Name>", Pattern.DOTALL);
	
	public static void main(String[] args) throws IOException {
		
		String file="<GetResponse>\r\n" + 
				"			<RuleInfo>\r\n" + 
				"				<Name>clarifyall</Name>\r\n" + 
				"				<DataType>RichTextFormat</DataType>\r\n" + 
				"			</RuleInfo>\r\n" + 
				"	</GetResponse>";
	    System.out.println(getTagValues(file).get(0)); 
	    
	}



	private static List<String> getTagValues(final String str) {
	    final List<String> tagValues = new ArrayList<String>();
	    final Matcher matcher = TAG_REGEX.matcher(str);
	    while (matcher.find()) {
	        tagValues.add(matcher.group(1));
	    }
	    return tagValues;
	}

 

 

 

 

Manohar Changed status to publish October 8, 2019
Add a Comment
You are viewing 1 out of 1 answers, click here to view all answers.
Write your answer.