[英]How to read multiple XML files in Java?
我有一个目录,其中包含多个类似格式的XML文件。 以下是一个例子
<students>
<forename>Joe</forename>
<surname>Bloggs</surname>
<DOB>01/01/1970</DOB>
<educationLevel>High School</educationLevel>
</students>
有没有一种方法可以遍历包含xml文件的目录(也许处于某种循环中?)并逐一读取xml文件?
获取驻留在目录中的XML文件
您可以使用以下方法遍历给定目录中的.xml
文件:
public static void readFiles(String directory) throws IOException {
File dir = new File(directory);
if (dir.exists() && dir.isDirectory()) {
File [] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
if (files != null) {
for (File file: files) {
String xml = new String(Files.readAllBytes(file.toPath()),
Charset.defaultCharset());
//parse xml
}
}
}
}
要解析XML,可以使用例如Jackson Object Mapper :
ObjectMapper xmlMapper = new XmlMapper();
YourPOJO value = xmlMapper.readValue(xml, YourPOJO.class);
检索数组中的所有学生标签,例如在python中,我想获取具有特定id的所有div:
link4 = "Any HTML Link"
data3 = requests.get(link4)
soup5 = BeautifulSoup(data3.text, "lxml")
soup6 = BeautifulSoup(str(soup5.findAll("div", { "id" : "specs-list" })),"lxml")
之后,您可以依次轮流浏览汤
我最终这样做:
public static void directoryLoop(File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
directoryLoop(fileEntry);
} else {
xmlReader(fileEntry.getName());
}
}
}
其中xmlReader(fileEntry.getName());
是我读取XML文件的方法,该方法将文件名作为参数。
假设您已经读取了xmlfile,并且知道文件名,则可以执行以下操作:
List<String> filenames;
for(String filename : filenames){
myXmlReadingMethod( "path of my Files " + filename);
}
希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.