gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:30:25 25 4
gpt4 key购买 nike

我有一些 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 文档:

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

关于使用 DocumentBuilderFactory 解析 Java XML - 空节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com