0

I have a simple XML

        <task id ="MyMethod">
            <taskParameter>"Redicted"</taskParameter>
            <taskParameter>"ServerInitiated"</taskParameter>
        </task>
        <task id ="NoRedictedMethod">
            <taskParameter>"NoRedicted"</taskParameter>
        </task>

and I want to parse it with Java and I try to print them with the proper nesting

        NodeList ParentList = doc.getElementsByTagName("task");
        for (int i = 0; i < ParentList.getLength(); i++) {
            System.out.println("Parent is "+ ParentList.item(i).getTextContent());

            NodeList childList = ParentList.item(i).getChildNodes();

            for (int j = 0; j < childList.getLength(); j++) {
                System.out.println("Clild is "+ childList.item(j).getTextContent());
            }
        }

my results are not right. What am I doing wrong?

PS. I want to print something like that

    Parent is MyMethod
    Clild is Redicted
    Clild is ServerInitiated
    Parent is NoRedictedMethod
    Clild is NoRedicted
2
  • What are you trying to print? How should your desired output look like? Commented May 21, 2017 at 18:44
  • I edited my question to answer you note Commented May 21, 2017 at 18:53

1 Answer 1

1

What you are calling as parent is an attribute node. So to retrieve that changes your code to:

Edited to avoid whitespace characters while parsing

NodeList ParentList = doc.getElementsByTagName("task");
        for (int i = 0; i < ParentList.getLength(); i++) {
            NamedNodeMap attributes = ParentList.item(i).getAttributes();

            for (int index = 0; index < attributes.getLength(); index++) {
                Node attribute = attributes.item(index);
                System.out.println("Parent is "+ attribute.getNodeValue());
            }

            NodeList childList = ParentList.item(i).getChildNodes();

            for (int j = 0; j < childList.getLength(); j++) {
               String text = childList.item(j).getTextContent();
               if (text.trim().length() != 0) {
                System.out.println("Clild is "+ text);
               }
            }
        }
Sign up to request clarification or add additional context in comments.

2 Comments

I found my problem. When it parsed the XML it also parses the blancks so I have chilldren for the first node: "\n\t\t\t", "Redicted", "\n\t\t\t\t" "ServerInitiated", "\n\t\t\t\t" and this is why when I print them they are messed up. What to do in this case?
Thanks a lot! I also tried to filter blanks wiht regural expression like: if(!childList.item(j).getTextContent().matches("^\n.*") ) which also works but your solution is way more elegant and generic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.