关于node.getNodeValue()的问题

hykwolf 2004-02-17 01:04:42
解析一段xml时
我获取到了一个node,节点的内容没有特殊字符
System.out.println(node.toString()); //正常打印了这段xml"<tt>....</tt>";
System.out.println(node.getNodeValue()); //打印出了null,奇怪;
System.out.println(node.getNodeName()); //正常打印出"tt";
node.setNodeValue("dsadf");
System.out.println(node.getNodeValue()); //竟然还是null;
System.out.println(((Element)node).getNodeValue()); //还是null;

这是什么问题啊?还是我不得法?
...全文
35 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXML { public static void main(String[] args) { try { // 得到DOM解析器的工厂实例 DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); // 从DOM工厂获得DOM解析器 DocumentBuilder dombuilder = domfac.newDocumentBuilder(); // 把要解析的XML文档转化为输入流,以便DOM解析器解析它 InputStream is = new FileInputStream("test.xml"); // 解析XML文档的输入流,得到一个Document Document doc = dombuilder.parse(is); // 得到XML文档的根节点 Element root = doc.getDocumentElement(); // 得到节点的子节点 NodeList books = root.getChildNodes(); if (books != null) { // 轮循子节点 for (int i = 0; i < books.getLength(); i++) { // 获取book节点 Node book = books.item(i); if (book.getNodeType() == Node.ELEMENT_NODE) { // 取得节点的属性值 String email = book.getAttributes().getNamedItem( "email").getNodeValue(); System.out.println(email); // 轮循子节点 for (Node node = book.getFirstChild(); node != null; node = node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("name")) { // 获得节点的文本值 String name = node.getFirstChild() .getNodeValue(); System.out.println(name); } if (node.getNodeName().equals("price")) { // 获得节点的文本值 String price = node.getFirstChild() .getNodeValue(); System.out.println(price); } } } } } } } // 异常处理 catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧