Search code examples
javaxmlxml-parsingcdata

How to get test value from CDATA in xml file using java


I'm trying to get the MethodName value from the CDATA node in xml file.
XML file looks like-

<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>   

What i have tried is only giving me all text value of this-
JAVA Code-

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 "";
    }  

But i want only methodName value from CDATA. Please help!


Solution

  • You already have method for retrieving CDATA content. To extract MethodName or other fields from this text there can be implemented custom parsing function, e.g.:

    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);
    }
    

    It splits text by commas, than splits each token by equal signs, than searches for supplied field name and returns text after equal sign (or null if not found). It can be called as follows:

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