生成解析XML的代码
时间: 2023-02-21 13:02:54 浏览: 72
生成XML解析代码的方法有很多种,具体方法取决于你使用的编程语言。下面是一些常用语言的例子:
- Python:可以使用标准库中的xml.etree.ElementTree模块来解析XML。
```
import xml.etree.ElementTree as ET
tree = ET.parse("sample.xml")
root = tree.getroot()
for child in root:
print(child.tag, child.attrib)
```
- Java:可以使用javax.xml.parsers包中的DocumentBuilder类来解析XML。
```
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;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File("sample.xml"));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
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("Item: " + eElement.getAttribute("name"));
}
}
```
- PHP:可以使用SimpleXML扩展来解析XML。
```
$xml = simplexml_load_file("sample.xml");
foreach ($xml->