简体   繁体   中英

Getting text value from java DOM

public static void printNode(NodeList nodeList, Document d) 
{
    for (int count = 0; count < nodeList.getLength(); count++)
    {           
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) 
        {               
            if(tempNode.getChildNodes().getLength()==1)
                {
                    if(tempNode.getNodeName()=="param-name")
                    {                               
                        tempNode = tempNode.getNextSibling();
                        System.out.println(tempNode.getTextContent());  
                    }

                }
            else if (tempNode.getChildNodes().getLength() > 1)              
                {                       
                printNode(tempNode.getChildNodes(),d);                  
                }

            else
            {
            print("ELSE")
            }
        }
    }
}

I just want to access and get text value from tag from this xml.file

<context-param>
    <param-name>A</param-name>
    <param-value>604800000</param-value>        
</context-param>

<context-param>
    <param-name>B</param-name>
    <param-value>50</param-value>
</context-param>

<context-param>
    <param-name>C</param-name>
    <param-value>1</param-value>        
</context-param>

but it's not work, the output is BLANKLINE _BLANKLINE_ BLANKLINE . . . .

So, anyone have an ideas ?

thank you very much .

You may want to try something like this:

public static void printNode(NodeList nodeList, Document d) {

  for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);

    if (node instanceof Element) {
      Element outerElement = (Element) node;
      NodeList paramElements = outerElement
          .getElementsByTagName("param-name");

      if (paramElements.getLength() != 1) {
        throw new RuntimeException("Wish I wasn't doing this by hand!");
      }

      Element element = (Element) paramElements.item(0);
      System.out.println(element.getTextContent());
    }
  }
}

You appear to be wanting the values which are siblings to the param-name nodes.

  1. Use the equals method to check object equality (not == )
  2. Whitespace creates text nodes

Consider using XPath :

  public static void printNode(Document d) {
    try {
      NodeList values = (NodeList) XPathFactory.newInstance()
          .newXPath()
          .evaluate("//param-value/text()", d, XPathConstants.NODESET);

      for (int i = 0; i < values.getLength(); i++) {
        System.out.println(values.item(i).getTextContent());
      }
    } catch (XPathExpressionException e) {
      throw new IllegalStateException(e);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM