解析XML的java片段
时间: 2023-08-18 10:07:04 浏览: 55
以下是使用Java解析XML的示例代码片段:
```java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class XMLParser {
public static void main(String[] args) {
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("根元素:" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("student");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("学号 : " + eElement.getAttribute("id"));
System.out.println("姓名 : " + eElement.getElementsByTagName("name").item(0).getTextContent());
System.out.println("年龄 : " + eElement.getElementsByTagName("age").item(0).getTextContent());
System.out.println("班级 : " + eElement.getElementsByTagName("class").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用Java内置的DOM解析器来解析名为 `input.xml` 的XML文件,并从该文件中提取学生信息。首先,我们创建一个 `DocumentBuilderFactory` 对象,并使用它来创建一个 `DocumentBuilder` 对象。然后使用 `DocumentBuilder` 对象解析XML文件,并将其转换为 `Document` 对象。接下来,我们使用 `Document` 对象获取根元素,并正常化XML文档。然后,我们使用 `getElementsByTagName` 方法获取名为 "student" 的元素列表,并遍历这个列表,提取每个学生的信息。最后,我们将学生信息打印到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)