有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查xml标记是否包含注释

如果不使用XML解析器库,如何检查XML标记是否包含注释

下面是我提出的代码,它适用于包含在标记中的注释,但不适用于已经嵌套在另一个注释中的标记

<ppn>750000015</ppn>
<ppn>750007015</ppn>
<ocn></ocn>
<!-- <inst> VU@</inst> is commented -->

Java代码:

 public static List<String> getTagList(String xml, String tag) {
        List<String> result = new ArrayList<>();
        if (xml != null && tag != null) {

            String startMarker = "<" + tag + "[\\s>]";
            Pattern pattern = Pattern.compile(startMarker);
            String endMarker = "</" + tag + ">";
            // Find the start of all such tags:
            Matcher matcher = pattern.matcher(xml);
            while (matcher.find()) {
                int startIndex = matcher.start();
                int endIndex = xml.indexOf(endMarker, matcher.start()) + endMarker.length();
                result.add(xml.substring(startIndex, endIndex));
            }
        }
        return result;
    }

共 (1) 个答案

  1. # 1 楼答案

    Without using a XML parser libary

    根据定义,任何可靠地检测XML元素中的注释的方法都是解析XML。因此,您的选择是:使用一个能正确完成这项工作的XML解析器库,还是编写一个不能完成这项工作的XML解析器

    如果你的老板不让你使用现成的XML解析器来完成这项任务,那么他们就是无能的;关于如何处理不称职老板的建议不在本论坛讨论范围之内