英文:
How to split XML tags into key and value pairs in Java
问题
我有一个包含不同 XML 标签的文本文件。我需要将这些标签拆分为键和值对。例如,以下标签应更改为 Version:1.5
预期输出:Version:1.5
是否有任何方法在不使用 XML 解析器的情况下实现这一点?
英文:
I have a text file which contains different XML tags. I need to split these tags into key and value pairs. For example the following tag should be changed to Version:1.5
<manifest:Version>1.5</manifest:Version>
Expected output: Version:1.5
Is there any way to do this without using XML Parser?
答案1
得分: 2
由于您已经提到您不想在这里使用任何xml-parser
,以下是适用于您情况的示例代码:
import java.util.Arrays;
import java.util.List;
public class BadXmlParser {
public static void main(String[] args) {
List<String> tags = Arrays.asList(
"<manifest:Name>java</manifest:Name>",
"<manifest:Version>1.8</manifest:Version>"
);
tags.forEach(tag -> {
String key = tag.substring(tag.indexOf(":") + 1, tag.indexOf(">"));
String value = tag.substring(tag.indexOf(">") + 1, tag.indexOf("</"));
System.out.println(key + ":" + value);
});
}
}
从不推荐在生产环境中使用的方法。
注意: 您应该自行添加验证逻辑,这只是提供的解析逻辑。
英文:
Since you already mentioned you don't want to use any xml-parser
here is a sample code which will work in you case-
import java.util.Arrays;
import java.util.List;
public class BadXmlParser {
public static void main(String[] args) {
List<String> tags = Arrays.asList("<manifest:Name>java</manifest:Name>", "<manifest:Version>1.8</manifest:Version>");
tags.forEach(tag -> {
String key = tag.substring(tag.indexOf(":") + 1, tag.indexOf(">"));
String value = tag.substring(tag.indexOf(">") + 1, tag.indexOf("</"));
System.out.println(key + ":" + value);
});
}
}
Never recommended approach to use in prod.
Note: You should put validation logic by you own this is just parsing logic provided
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论