3

I have some Java code to parse an XML file. My code is returning null for my nodes, however.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse( new File( path ) );
rootElement = doc.getDocumentElement();
String str = rootElement.getLocalName();

When I print str, I get null. The path to the XML file is correct. Any ideas what might be the problem?

1 Answer 1

3

Do you want the tag name? Use rootElement.getTagName();

From the Java docs:

public String getLocalName()

Returns the local part of the qualified name of this node. For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as Document.createElement(), this is always null. Since: DOM Level 2.

public String getTagName()

The name of the element. If Node.localName is different from null, this attribute is a qualified name. For example, in:

 <elementExample id="demo"> ...
 </elementExample> , 

tagName has the value "elementExample". Note that this is case-preserving in XML, as are all of the operations of the DOM. The HTML DOM returns the tagName of an HTML element in the canonical uppercase form, regardless of the case in the source HTML document.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's great. What about getting text at a node, for example <node>text </node> ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.