roymustang86
roymustang86

Reputation: 8623

java Convert Element to string

I am looking to get only the tag name, and not it's children.

I have an xml like this:

  <RESPONSE>
    <RESULT>                                              !--TableName
       <ADDRESS1>123 Main Street</ADDRESS1>               !--ColumnName
       <ZIP>12345</ZIP>                                   !--ColumnName
    </RESULT>
    <RESULT>                                              !--TableName
      <ADDRESS1>245 Elm Street</ADDRESS1>                 !--ColumnName
      <ZIP>45678</ZIP>                                    !--ColumnName
   </RESULT>
   <VIN>                                                  !--TableName
      <VIN_NUM>1K45678RTW23</VIN>                         !--ColumnName
   </VIN>
   ….
</REPSONSE>

I am trying to dynamically save the xml into it's appropriate table and column names. So, I want to extract whatever the first element is, and assign it to a table name variable, and then it's children as columns.

Here is what I am doing so far:

    private void extractToTableSet(Document doc, int appseqno ) throws Exception
{
    NodeList responseList = doc.getElementsByTagName("RESPONSE");
    for (int i = 0; i < responseList.getLength(); i++) {
        Node currentNode = responseList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            Element tableElement = (Element) responseList.item(i);
            if (tableElement != null && tableElement.hasChildNodes()) {
                for (columnNode = tableElement.getFirstChild(); columnNode != null; columnNode = columnNode.getNextSibling()) {
                    if (columnNode.getNodeType() == Node.TEXT_NODE) {
                        columnName = columnNode.getNodeValue;
                    }
                }
            }
        }
    }
}

This way I am only able to get the values in the child nodes. Is there a way to get the name of the Element tags? Like I want to extract the value RESULT from the Document object.

Upvotes: 0

Views: 3220

Answers (2)

user3487063
user3487063

Reputation: 3682

To get element's tagname :

Element tableElement = (Element) responseList.item(i);
    String tagname = tableElement .getTagName();

Upvotes: 1

M A
M A

Reputation: 72884

In DOM, an element name is retrieved using Node.getNodeName().

Example:

if(node.getNodeType() == Node.ELEMENT_NODE) {
    String elementName = node.getNodeName();
    ...
}

Upvotes: 1

Related Questions