Getting specific Substring from a large string
<emp>
<name>Jhon</name>
<sal>2000</sal>
</emp>
I will get this xml as string.I need to generate an xml fi开发者_运维知识库le from the string and i need to name the generated xml file with name tag.eg:Jhon.xml.please provide me some pointers to do the same in java with out using parsers.
Using string substring or regex is parsing the file. I assume you mean you don't want to have to parse every detail.
If you know each element is on a line by itself 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)) {
}
}
Although caution applies when using regex over xml... this will do it in one line:
String filename = input.replaceAll("(?s).*<name>(.*)</name>.*<ruleId>(.*)</ruleId>.*<ruleVersion>(.*)</ruleVersion>.*", "$1_$2_$3.xml");
The (?s)
is important - it turns on the "dot matches newline" switch, so your input can contain multiple lines (ie embedded newlines) but be treated as a single line.
Here's a test of this line 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
精彩评论