如何在Java中将XML标签拆分为键值对。

huangapple go评论59阅读模式
英文:

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&lt;String&gt; tags = Arrays.asList(&quot;&lt;manifest:Name&gt;java&lt;/manifest:Name&gt;&quot;, &quot;&lt;manifest:Version&gt;1.8&lt;/manifest:Version&gt;&quot;);
        tags.forEach(tag -&gt; {
            String key = tag.substring(tag.indexOf(&quot;:&quot;) + 1, tag.indexOf(&quot;&gt;&quot;));
            String value = tag.substring(tag.indexOf(&quot;&gt;&quot;) + 1, tag.indexOf(&quot;&lt;/&quot;));
            System.out.println(key + &quot;:&quot; + value);
        });
    }
}

Never recommended approach to use in prod.

Note: You should put validation logic by you own this is just parsing logic provided

huangapple
  • 本文由 发表于 2020年8月23日 15:52:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63544630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定