SOP
SOP

Reputation: 801

xml DOM traversal using java : list.item(i).getFirstChild()

I am trying to iterate through XML tags and I use list.item(i).getFirstChild(); but it returns :[# text: ]. Acoording to me this method should return either "tag name" or null, but here it's returning alternate tagname and [# text: ] i.e.

[# text: ]

tagname

[# text: ]

tagname the code I am using is:

public  void readXML() throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        String rootNode=null;
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("C:/Users/ve00p5199/Desktop/xml/test.xml"));
        NodeList list = doc.getElementsByTagName("*");

        for (int i = 0; i < list.getLength(); i++) {
            //System.out.println(list.item(i).getNodeName());
            if(list.item(i).getNodeName().equalsIgnoreCase("shape")||list.item(i).getNodeName().equalsIgnoreCase("Textbox")||list.item(i).getNodeName().equalsIgnoreCase("Button")){
//              System.out.println(list.item(i).getNodeName());
                Node node = findPropertyTagAndValue(list.item(i).getFirstChild(), "PropertyValue", "conditionContainer");
                if (node != null) {
                    System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent());
                    DOMSource src = new DOMSource(list.item(i));
                    StringWriter sr = new StringWriter();
                    Result res = new StreamResult(sr);
                    tx.transform(src, res);
                    System.out.println(sr);
                }
            }
        }
    }

    public static Node findPropertyTagAndValue(Node node, String propertyTag, String propertyValue) {
        if (node == null) {
            // The node we're looking for does not exist
            return null;
        } else if (node.getNodeType() != Node.ELEMENT_NODE) {
            // Move to the next sibling node
            return findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
        } else if (node.getNodeName().equalsIgnoreCase(propertyTag) && node.getTextContent().equalsIgnoreCase(propertyValue)) {
            // We found the node we are looking for
            return node;
        } else if (node.hasChildNodes()) {
            // Check into the child nodes
            Node childNode = findPropertyTagAndValue(node.getFirstChild(), propertyTag, propertyValue);
            if (childNode == null) {
                // Nothing found in child node, so move to next sibling
                childNode = findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
            }
            return childNode;
        } else {
            // Move to the next sibling
            return findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
        }
    }

My XML iS:

<Diagram>
                <Widgets>

                    <Shape>
                        <ShapeType>H2</ShapeType>
                        <Annotation>
                            <Properties>
                                <PropertyValue PropertyName="field_label">label.modelSeriesCd</PropertyValue>
                                <PropertyValue PropertyName="ContainerType">conditionContainer</PropertyValue>
                            </Properties>
                        </Annotation>
                        <FootnoteNumber>1</FootnoteNumber>
                        <Name>label.modelSeriesCd</Name>
                        <Rectangle>
                            <Rectangle X="14" Y="94" Width="43" Height="12" />
                        </Rectangle>
                    </Shape>
                    </Diagram>
                </Widgets>

please explain...

Upvotes: 0

Views: 733

Answers (1)

Madhan
Madhan

Reputation: 5818

NodeList list = object.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        Node listNode = nodeList.item(i);
        if (Node.ELEMENT_NODE == listNode.getNodeType()) {
            String nodeName = listNode.getNodeName();
            if (nodeName.equalsIgnoreCase("shape")
                    || nodeName.equalsIgnoreCase("Textbox")
                    || nodeName.equalsIgnoreCase("Button")) {

                Node node = findPropertyTagAndValue(listNode, "PropertyValue", "conditionContainer");
                if (node != null) {
                    System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent());
                    DOMSource src = new DOMSource(list.item(i));
                    StringWriter sr = new StringWriter();
                    Result res = new StreamResult(sr);
                    tx.transform(src, res);
                    System.out.println(sr);
                }
            }
        }
    }


 /**
 * No Need to check for all those things. Only * will return all elements
 * including #text node. If you give proper node name then it will return
 * those node's only That's why there's node need for checking ELEMENT_NODE
 * in finding propertTags
 */

  public static Node findPropertyTagAndValue(Node node, String propertyTag, String propertyValue) {
    if (Node.ELEMENT_NODE == node.getNodeType()) {
        NodeList nodeList = ((Element) node).getElementsByTagName(propertyTag);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node listNode = nodeList.item(i);
            if (listNode.getTextContent().equalsIgnoreCase(propertyValue)) {
                return listNode;
            }
        }
    }
    return null;
}

Upvotes: 1

Related Questions