如何获取xml中的属性
时间: 2024-05-02 08:18:12 浏览: 14
在Java中,可以使用DOM或SAX解析器来获取XML中的属性。
DOM解析器:
1. 通过DocumentBuilderFactory创建DocumentBuilder对象。
2. 通过DocumentBuilder对象的parse方法将XML文件解析为Document对象。
3. 通过Document对象的getElementsByTagName方法获取指定标签名的元素节点列表。
4. 遍历元素节点列表,通过Element对象的getAttribute方法获取指定属性名的属性值。
示例代码:
```
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("example.xml"));
NodeList nodeList = doc.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String id = element.getAttribute("id");
String name = element.getAttribute("name");
System.out.println("id: " + id + ", name: " + name);
}
```
SAX解析器:
1. 通过SAXParserFactory创建SAXParser对象。
2. 自定义实现DefaultHandler的子类,并重写startElement方法,在该方法中获取指定标签名的属性值。
3. 通过SAXParser对象的parse方法将XML文件解析为Document对象,并传入自定义的DefaultHandler对象。
示例代码:
```
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("book".equals(qName)) {
String id = attributes.getValue("id");
String name = attributes.getValue("name");
System.out.println("id: " + id + ", name: " + name);
}
}
};
saxParser.parse(new File("example.xml"), handler);
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)