- xml文件的读取解析等操作,我这边采用的是hutool工具,用来读取xml文件下各个标签的内容以及其中的属性,均可打印出来,但是只用之前要引hutool包,hutool工具还是比较好用的,推荐使用
hutool工具文档 - 废话不多说,直接上代码,我要读取的文件如下
- 我要读取其中标签的属性,并输出,代码如下
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.List;
public class xmlTest {
public static void ReadXmlTest(){
String xml = "D:\\WorkSpaceDxw\\Hutool\\src\\main\\java\\Hutool\\test.xml";
Document document = XmlUtil.readXML(xml);
Element goalElement = XmlUtil.getElementByXPath("//html",document);
List<Element> elementList = XmlUtil.getElements(goalElement,"unit");
for (Element element : elementList){
List<Element> list= XmlUtil.getElements(element,"field");
Console.log(element.getAttribute("class") + " " + element.getAttribute("name") + " " + element.getAttribute("label"));
for (Element element1 : list){
Console.log(element1.getAttribute("name") + " " + element1.getAttribute("path")+"."+ element1.getAttribute("item") + " " + element1.getAttribute("label"));
}
Console.log();
}
}
public static void main(String[] args) {
ReadXmlTest();
}
}
- 结果如下: