2009-08-18 65 views
12
try { 
     String data = "<a><b c='d' e='f'>0.15</b></a>"; 
     DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
       .newInstance(); 
     DocumentBuilder documentBuilder = documentBuilderFactory 
       .newDocumentBuilder(); 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(data)); 
     Document document = documentBuilder.parse(is); 

     NodeList nl = document.getElementsByTagName("b"); 
     Node n = (Node) nl.item(0); 
     System.out.println(n.getNodeValue()); 
    } catch (Exception e) { 
     System.out.println("Exception " + e); 

    } 

我期待它打印0.15,但它打印出null。有任何想法吗?使用DOM获取节点值的Java XML解析

编辑:这奏效了

 if (n.hasChildNodes()) 
      System.out.println(n.getFirstChild().getNodeValue()); 
     else 
      System.out.println(n.getNodeValue()); 

回答

6

尝试从元素而不是从节点提取它:

try { 
    String data = "<a><b c='d' e='f'>0.15</b></a>"; 
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
      .newInstance(); 
    DocumentBuilder documentBuilder = documentBuilderFactory 
      .newDocumentBuilder(); 
    InputSource is = new InputSource(); 
    is.setCharacterStream(new StringReader(data)); 
    Document document = documentBuilder.parse(is); 

    NodeList nl = document.getElementsByTagName("b"); 
    Element el = (Element) nl.item(0); 
    Text elText = (Text) el.getFirstChild(); 
    String theValue = elText.getNodeValue(); 
    System.out.println(theValue); 
} catch (Exception e) { 
    System.out.println("Exception " + e); 
} 
+0

@mkal - 我只是编辑输出的nodeValue而不是文本实例! – karim79 2009-08-18 01:06:10

11

这是因为an element in fact has no nodeValue。相反,它有一个文本节点作为孩子,它有你想要的nodeValue

总之,您需要对getNodeValue()元素节点的第一个孩子。

有时候元素包含多个文本节点,因为他们有一个最大尺寸,在这种情况下,你需要的东西一拉这个,从页面链接前面:

public static String getNodeValue(Node node) { 
    StringBuffer buf = new StringBuffer(); 
    NodeList children = node.getChildNodes(); 
    for (int i = 0; i < children.getLength(); i++) { 
     Node textChild = children.item(i); 
     if (textChild.getNodeType() != Node.TEXT_NODE) { 
      System.err.println("Mixed content! Skipping child element " + textChild.getNodeName()); 
      continue; 
     } 
     buf.append(textChild.getNodeValue()); 
    } 
    return buf.toString(); 
} 
+0

很好的解释,并非常感谢功能卓越。像冠军一样工作。 – 2012-09-14 12:05:23

3
System.out.println(n.getFirstChild().getNodeValue()); 
1

如果节点没有进一步嵌套的后代,比n.getTextContent()工作得很好。

2
private String getTextValue(Element element, String string) { 
    String textVal = null; 
    NodeList nl = element.getElementsByTagName(string); 
    if(nl != null && nl.getLength() > 0) { 
     Element el = (Element)nl.item(0); 
     textVal = el.getFirstChild().getNodeValue(); 
    } 

    return textVal; 

} 
1

您可以使用jOOX作为标准DOM的包装,以简化您的代码。

String data = "<a><b c='d' e='f'>0.15</b></a>"; 
String value = $(data).find("b").text(); 

你也可以有jOOX转换该值加倍,例如:

Double value = $(data).find("b").text(Double.class);