如何在java'中获取文本节点的标记名;s org.w3c.dom.Node

如何在java'中获取文本节点的标记名;s org.w3c.dom.Node,java,xml-parsing,w3c,xmlnode,Java,Xml Parsing,W3c,Xmlnode,在该接口的文档中,它声明textnodes都会返回“#text”作为其名称,而不是实际的标记名。但是对于我所做的,标签名是必要的 // I'm using the following imports import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeM

在该接口的文档中,它声明textnodes都会返回“#text”作为其名称,而不是实际的标记名。但是对于我所做的,标签名是必要的

// I'm using the following imports
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;


// In the .xml input file
<country>US</country>  // This is a "text node" .getTextContent()
                       // returns "US", I need "country" and .getNodeName() 
                       // only returns "#text"
//我正在使用以下导入
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入org.w3c.dom.Document;
导入org.w3c.dom.NamedNodeMap;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
导入org.xml.sax.EntityResolver;
导入org.xml.sax.InputSource;
//在.xml输入文件中
US//这是一个“文本节点”。getTextContent()
//返回“US”,我需要“country”和.getNodeName()
//仅返回“#文本”
如何访问标记名?无论如何,这一定是可能的,我不介意一个骇人的解决方案

文件:


谢谢。

我认为您误解了所涉及的节点。此XML:

<country>US</country>
美国
。。。包含两个节点:

  • country
    元素
  • 文本节点,包含我们的内容
元素不是文本节点,文本节点没有元素名称,因为它不是元素。重要的是要了解这些节点是不同的。我相信这就是你所有困惑的根源

如果当前正在查看文本节点,可以使用
node.getParentNode().getNodeName()
获取元素名称。或者从元素节点调用
getTextContent()