【问题标题】:Retrieving XML node names检索 XML 节点名称
【发布时间】:2012-07-16 07:35:40
【问题描述】:

我正在尝试使用“node.getNodeName()”从 XML 文件中检索所有节点的名称。这样做时,每个节点名称的前面和后面都是“#text”。因此,我也没有得到确切的节点数。我希望在检索名称时消除“#text”。我怎么做??

【问题讨论】:

  • 如果你想要更快的反馈,你最好用“java”标记这个问题;)
  • 我使用了 SAXBuilder.. 它按我的意愿工作..

标签: java xml


【解决方案1】:

这样:

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

是你搜索的吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2017-10-10
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多