如何使用java从xml文件中的CDATA获取测试值

如何使用java从xml文件中的CDATA获取测试值,java,xml,xml-parsing,cdata,Java,Xml,Xml Parsing,Cdata,我正在尝试从xml文件中的CDATA节点获取MethodName值。 XML文件看起来像- <params> <param index="0"> <value> <![CDATA[{PackageResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/E

我正在尝试从xml文件中的CDATA节点获取MethodName值。
XML文件看起来像-

<params>
            <param index="0">
              <value>
                <![CDATA[{PackageResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedPackageResponse.json, ProviderRequest=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderRequest.json, ParameterFilePath=./src/test/resources/TestData/RequestParameter/InstantCash/GetAnywherePayoutAgents.json, ProviderResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderResponse.json, MethodName=GetAnywherePayoutAgents}]]>
              </value>
            </param>
          </params>   

我所尝试的只是给我这个-
JAVA代码-

public static String getCharacterDataFromElement(Element e) {

        NodeList list = e.getChildNodes();
        String data;

        for(int index = 0; index < list.getLength(); index++){
            if(list.item(index) instanceof CharacterData){
                CharacterData child = (CharacterData) list.item(index);
                data = child.getData();

                if(data != null && data.trim().length() > 0)
                    return child.getData();
            }
        }
        return "";
    }  
公共静态字符串getCharacterDataFromElement(元素e){
NodeList list=e.getChildNodes();
字符串数据;
对于(int index=0;index0)
返回child.getData();
}
}
返回“”;
}  

但我只需要CDATA中的methodName值。请帮忙

您已经有了检索CDATA内容的方法。要从此文本中提取MethodName或其他字段,可以实现自定义解析功能,例如:

public static String getMethodName(String source, String fieldName) {
        if(source.startsWith("{") && source.endsWith("}")) {
            source = source.substring(1, source.length() - 1);
        }
        return Arrays.asList(source.split(",")).stream()
                .map(s -> s.trim().split("="))
                .filter(s -> fieldName.equals(s[0]))
                .map(s -> s[1])
                .findFirst()
                .orElse(null);
}
它以逗号分隔文本,然后以等号分隔每个标记,然后搜索提供的字段名并返回等号后的文本(如果未找到,则返回null)。它可以被称为:

String cdata = getCharacterDataFromElement(element);
String methodName = getMethodName(cdata , "MethodName");

看起来像是一个基本字符串操作的作业,可以拆分
然后
=
,使用正则表达式提取目标子字符串,或者使用带有相关分隔符的扫描程序提取目标标记。明显的建议是对值使用标准语法(XML或JSON),而不是使用您编造的东西。但如果必须使用非标准语法,则只需执行一些自定义解析。整个getCharacterDataFromElement方法可以替换为该方法,该方法是元素从节点继承的。文本内容本身看起来像未加引号的JSON,因此您应该将其传递给JSON解析器,然后检索与
“MethodName”
键对应的值。感谢@danil,它可以工作,但对于lambda表达式,我们需要Java8或更高版本。