java - 解析 Node 内的 XML

标签 java xml parsexml

XML

<?xml version="1.0"?>
<Employees>
    <Employee emplid="1111" type="admin">
        <firstname>John</firstname>
        <lastname>Watson</lastname>
        <age>30</age>
        <email>johnwatson@sh.com</email>
    </Employee>
    <Employee emplid="2222" type="admin">
        <firstname>Sherlock</firstname>
        <lastname>Homes</lastname>
        <age>32</age>
        <email>sherlock@sh.com</email>
    </Employee>
    <Employee emplid="3333" type="user">
        <firstname>Jim</firstname>
        <lastname>Moriarty</lastname>
        <age>52</age>
        <email>jim@sh.com</email>
    </Employee>
    <Employee emplid="4444" type="user">
        <firstname>Mycroft</firstname>
        <lastname>Holmes</lastname>
        <age>41</age>
        <email>mycroft@sh.com</email>
    </Employee>
</Employees>

代码

FileInputStream file = new FileInputStream(new File("/Users/Desktop/employees.xml"));                 
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();             
DocumentBuilder builder =  builderFactory.newDocumentBuilder();             
Document xmlDocument = builder.parse(file); 
XPath xPath =  XPathFactory.newInstance().newXPath();   
System.out.println("*************************");
String expression = "/Employees/Employee/firstname";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}

通过使用上面的代码,我成功地获取了John,Sherlock,Jim,Mycroft。如果我想得到 emplid="1111"type="admin"John,emplid="2222"type="admin"Sherlock,emplid="3333"type="user"Jim,emplid= 我该怎么办“4444”类型=“用户”Mycroft。非常感谢任何建议或引用链接。

最佳答案

看看 API:

String expression = "/Employees/Employee";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {
    Node employeeNode = nodeList.item(i);
    String emplId = employeeNode.getAttributes().getNamedItem("emplid").getNodeValue();
}

( http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html#getAttributes() )

关于java - 解析 Node 内的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22321301/

相关文章:

java - 如何修复 HIbernate 5.4.17 中的实体未映射错误?

java - 什么是从 Java 生成任意 XML 的好库?

java - Android kotlin/java - ReclerView 在 Holder/xml 中隐藏部件时的奇怪行为

python - 使用 lxml python 解析 xhtml

jquery - 如何在旧版Jquery文件中添加jquery Xml解析功能?

java - 在java中初始化字符串数组的合法方法是什么?

java - 如何使用 Spring 进行参数化依赖注入(inject)?

java - Android 比较两个微调器和新 Activity 的 Intent

java - 如何从 hibernate 映射文件生成 Jaxb-XML-Beans?

javascript - jQuery $.parseXML 不适用于 Chrome 或 FireFox