2013-04-26 62 views
0
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") 
      } 
     } 
    } 
} 

我只是想从标签从这个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> 

访问和获取文本价值,但它不能正常工作,输出 BLANKLINE _BLANKLINE_ BLANKLINE 。 。 。 。

那么,有谁有想法?

非常感谢。

+0

也许http://stackoverflow.com/questions/773012/getting-xml-node-text-value-with-java-dom?rq = 1可以帮助 – reporter 2013-04-26 08:47:14

+4

不要使用'=='作为st环比较。使用'equals()' – NilsH 2013-04-26 08:48:37

+1

我建议将您的问题放在帖子的顶部,以便读者在阅读代码之前了解上下文。 – 2013-04-26 09:03:45

回答

1

你似乎想这是兄弟的param-name节点的值。

  1. 使用equals方法检查对象平等(不==
  2. 空白创建text nodes

考虑使用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); 
    } 
    } 
+0

非常感谢你们ALL:D – user2322921 2013-04-29 01:41:24

1

你可能想尝试这样的:

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