How To Convert Java Regex To Extract Text Between Tags?

2.03K 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>

Changed status to publish
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;
	}

 

 

 

 

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