微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用DocumentBuilderFactory进行Java XML解析-空节点?

我有一些Java代码来解析XML文件.但是,我的代码为我的节点返回null.

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

当我打印str时,我得到null. XML文件的路径正确.任何想法可能是什么问题?

解决方法:

您想要标签名称吗?使用rootElement.getTagName();

从Java文档中:

公共字符串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.

公共字符串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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。