gpt4 book ai didi

java - java中XML解析器的绝对路径

转载 作者:行者123 更新时间:2023-12-01 11:39:29 32 4
gpt4 key购买 nike

我有以下代码来打开 XML 文件进行解析。我的问题是变量 designPath:它目前必须是我的程序根目录的相对路径。但是,当我传递绝对路径时,它不起作用。

// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();

// Load and Parse the XML document
// document contains the complete XML as a Tree
Document document = builder.parse(ClassLoader.getSystemResourceAsStream(designPath));

如何使用 designPath 变量中的绝对路径或相对路径来实现此操作?

问题出在函数 ClassLoader.getSystemResourceAsStream 上,该函数从用于加载类的搜索路径中获取“指定名称的资源”。根据Java文档,但我希望能够将它与绝对路径一起使用。

请注意,我的 designPath 可能与我的程序位于不同的驱动器上。

最佳答案

改为传入InputStream:

// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();

// Load and Parse the XML document
// document contains the complete XML as a Tree
File file = new File(PATH_TO_FILE);
InputStream inputStream = new FileInputStream(file);

Document document = builder.parse(inputStream);

或者简单地传递一个新的File对象

// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();

// Load and Parse the XML document
// document contains the complete XML as a Tree
Document document = builder.parse(new File(PATH_TO_FILE));

关于java - java中XML解析器的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659947/

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