How to use Java’s org w3c. dom. Get text from node_ TagName for node

In the interface's documentation, it declares that text nodes return "#text" as their name instead of the actual tag name But for what I'm doing, the tag name is necessary

// 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"

How can I access tag names? This must be some kind of possibility, and I don't mind a hackish solution

file:

http://www.w3schools.com/dom/dom_nodetype.asp

http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Node.html

thank you.

Solution

I think you misunderstood which nodes are involved This XML:

<country>US</country>

... contains two nodes:

>Country element > text node, the content is us

The element is not a text node, and the text node has no element name because it is not an element It is important to understand that these are different nodes I believe this is the root of all your confusion

If you are currently viewing a text node, you can use node getParentNode(). Getnodename() to get the element name Or from the element node, you can call gettextcontent()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>