java 检索 XML 节点名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10784036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving XML node names
提问by varsha
I am trying to retrieve the names of all the nodes from XML file using "node.getNodeName()". While doing so, every node name is preceeded and followed by "#text". Because of that, i am not getting the exact count of nodes as well. I want "#text" to be eliminated while retrieving the names. How do i do that??
我正在尝试使用“node.getNodeName()”从 XML 文件中检索所有节点的名称。这样做时,每个节点名称前后都有“#text”。因此,我也没有得到节点的确切数量。我希望在检索名称时消除“#text”。我怎么做??
回答by Istao
With that :
接着就,随即 :
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());
}
}
}
I get :
我得到:
name is : a
name is : o
name is : u
Is that you search ?
是你搜索吗?