gpt4 book ai didi

java - 为什么 Element::getElementsByTagNameNS 会失败?

转载 作者:行者123 更新时间:2023-11-29 05:41:53 25 4
gpt4 key购买 nike

给定 XML 实例文档:

<foo:A xmlns:foo="http://foo" >
<foo:ListRecords>
<foo:record>
</foo:record>
</foo:ListRecords>
</foo:A>

以下代码:

import java.io.File;

import javax.xml.parsers.*;
import org.w3c.dom.*;


public class FooMain {

public static void main(String args[]) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("record.xml"));
Element rootElement = document.getDocumentElement();
NodeList records1 = rootElement.getElementsByTagNameNS("*", "record");
NodeList records2 = rootElement.getElementsByTagNameNS("http://foo", "record");
NodeList records3 = rootElement.getElementsByTagName("foo:record");
System.out.printf("%d records1 found.\n", records1.getLength());
System.out.printf("%d records2 found.\n", records2.getLength());
System.out.printf("%d records3 found.\n", records3.getLength());
}
}

打印:

0 records1 found.
0 records2 found.
1 records3 found.

最佳答案

您需要一个命名空间感知的解析器。 By default , JDK 解析器不支持命名空间。

将您的代码更改为如下所示:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

关于java - 为什么 Element::getElementsByTagNameNS 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175608/

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