Getting a specific substring from a large string

<emp> <name>Jhon</name> <sal>2000</sal> </emp> 

I will get this xml as a string. I need to generate an XML file from a string, and I need to specify a generated xml file called tag.eg:Jhon.xml.please to provide me with some pointers to do the same in java without using parsers.

+4
source share
2 answers

Using a string substring or regular expression parses the file. I assume that you mean that you do not want to analyze every detail.

If you know that each item is on the same line, you can use the following approach.

 BufferedReader br = String line; while((line = br.readLine()) != null) { String[] parts = line.split("[<>]"); String tag = parts[1]; String value = parts[2]; if ("name".equals(tag)) { } else if ("ruleId".equals(tag)) { } else if ("ruleVersion".equals(tag)) { } } 
+2
source

Although you should be careful when using regex over xml ... this will be done on one line:

 String filename = input.replaceAll("(?s).*<name>(.*)</name>.*<ruleId>(.*)</ruleId>.*<ruleVersion>(.*)</ruleVersion>.*", "$1_$2_$3.xml"); 

Important (?s)

Here check this line which you can run:

 public static void main(String[] args) throws Exception { String input = "<name>remove use case</name>\n <ruleId>2161</ruleId>\n <ruleVersion>0.0.1</ruleVersion>\n <ruleStatus>New</ruleStatus>\n <nuggetId>489505737</nuggetId>\n <icVersionId>50449</icVersionId>\n <rlVersion>1.0</rlVersion>\n <modelVersion>1.0</modelVersion>\n <attributes>\n <attribute>\n <attributeName/>\n <value/>\n </attribute>\n </attributes>\n <notes></notes>"; String filename = input.replaceAll("(?s).*<name>(.*)</name>.*<ruleId>(.*)</ruleId>.*<ruleVersion>(.*)</ruleVersion>.*", "$1_$2_$3.xml"); System.out.println(filename); } 

Output:

 remove use case_2161_0.0.1.xml 
0
source

All Articles