检索XML节点名称

3
我正在尝试使用“node.getNodeName()”从XML文件中检索所有节点的名称。在这样做时,每个节点名称都会在前面和后面加上“#text”。由于这个问题,我无法准确地获取节点数量。我想要在检索名称时消除“#text”。我该怎么做?

如果你想要更快的反馈,最好给这个问题打上“java”的标签 ;) - javatutorial
我使用了SAXBuilder..它按照我的期望工作了。 - varsha
1个回答

13

那么:

package com.hum;

import java.io.InputStreamReader;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author herve
 */
public class PrintNameXML
{
  public static void main(String[] args) throws Exception
  {
    String xml = "<a><o><u>ok</u></o></a>";
    Document doc = 
     DocumentBuilderFactory
     .newInstance()
     .newDocumentBuilder()
     .parse(new InputSource(new StringReader(xml)));
    NodeList nl = doc.getElementsByTagName("*");
    for (int i = 0; i < nl.getLength(); i++)
    {
      System.out.println("name is : "+nl.item(i).getNodeName());
    }
  }
}

我得到:

name is : a
name is : o
name is : u

这是你要搜索的内容吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接