使用 JDOM 解析 XML 文件时出错
我有这个 XML 文档:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<Achild>
.....
</Achild>
</RootElement>
如何检查文档是否包含 Achild
元素?我尝试过
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
try {
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(configFile);
final Node parentNode = doc.getDocumentElement();
final Element childElement = (Element) parentNode.getFirstChild();
if(childElement.getNodeName().equalsIgnoreCase(...
,但它给了我一个错误(childElement
为空)。
I have this XML document:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<Achild>
.....
</Achild>
</RootElement>
How can I check if the document contains Achild
element or not? I tried
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
try {
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(configFile);
final Node parentNode = doc.getDocumentElement();
final Element childElement = (Element) parentNode.getFirstChild();
if(childElement.getNodeName().equalsIgnoreCase(...
but it gives me an error (childElement
is null).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您将
#text
节点(位于
和
之间)作为第一个子节点(这很漂亮)常见错误),例如:返回:
使用替代:
想要的结果:
编辑:
还有第二种方法使用
DocumentBuilderFactory.setIgnoringElementContentWhitespace< /code>
方法:
但是,这只适用于验证模式,因此您需要在 XML 文档中提供 DTD:
并设置
factory.setValidating(true)
。完整示例:原始代码想要的结果:
I think that you're getting
#text
node (that between<RootElement>
and<Achild>
) as first child (that's pretty common mistake), for example:Returns:
Use instead:
Wanted result:
EDIT:
There is second way using
DocumentBuilderFactory.setIgnoringElementContentWhitespace
method:However this works only in validating mode, so you need to provide DTD in your XML document:
and set
factory.setValidating(true)
. Full example:Wanted result with original code:
听起来 .getFirstChild() 返回一个包含“”和“”之间空格的文本节点,在这种情况下,您需要前进到下一个同级节点才能到达您期望的位置。
It sounds like .getFirstChild() is returning you a text node containing the white space between "" and "", in which case you would need to advance to the next sibling node to get to where you expect.