你是资深java开发工程师,请写一个解析XML的工具类
时间: 2023-11-22 20:54:49 浏览: 132
好的,以下是一个简单的解析XML的工具类的示例代码:
```java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlParser {
public static void parseXml(String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xml);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("employee");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getAttribute("id");
String firstName = element.getElementsByTagName("firstName").item(0).getTextContent();
String lastName = element.getElementsByTagName("lastName").item(0).getTextContent();
String email = element.getElementsByTagName("email").item(0).getTextContent();
String salary = element.getElementsByTagName("salary").item(0).getTextContent();
System.out.println("Employee ID: " + id);
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Email: " + email);
System.out.println("Salary: " + salary);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上面代码中可以解析一个XML字符串,遍历其中的employee元素,并输出其中的id、firstName、lastName、email和salary属性。在实际使用中,xml参数可以替换为输入流或文件路径等其他形式,以适应不同的需求。