1.分析步骤:
- 一、获取读取文档的对象SaxReader。
- 二、public Document read(File file) : 将XML文档读取到内存中,生成Document对象。
- 三、public Element getRootElement() : 获取根标签元素对象。
- 四、public List elements(String elementName) :获取指定名称的子标签元素对象,并将象封装到List集合中。
- 五、遍历集合,获取子标签内元素。
- 六、public Element element(String elementName) : 获取指定名称的子标签元素对象。
-七、 public String getText() : 获取Element标签体中的内容作为字符串返回。 - 八、(6、7合并(获取子标签文本内容)):
两步:1.获取到指定名称的子标签对象 2.获取到子标签对象的文本内容。 - 九、public Arrtibute attribute(String attributeName) :
获取指定名称的属性对象,返回Arrtibute对象。 - 十、public String getValue() : 获取属性对象的属性值,作为字符串返回。
- 十一、(9、10合并):
public Arrtibute attribute(String attributeName) : 获取指定名称的属性对象,返回Arrtibute对象.
public Arrtibute attributeValue(String attributeName) :找到指定名称的属性对象 2.获取到属性对象的属性值内容。
2.XML文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210414211357841.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Z5NTEy,size_16,color_FFFFFF,t_70#pic_center)
3.代码:
public class TextXml {
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("day15_XML_meiju\\Students.xml"));
Element rootElement = document.getRootElement();
List<Element> element = rootElement.elements("student");
for (Element elements : element) {
Element nameElement = elements.element("name");
String name = nameElement.getText();
String age = elements.elementText("age");
String address = elements.elementText("address");
Attribute attribute = elements.attribute("ID");
String id = attribute.getValue();
String s = elements.attributeValue("sex");
System.out.println("学号为:" + id + ",姓名是:" + name + ",年龄是:" + age + ",性别为:" + s + ",地址是" + address);
}
}
}
4.运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210414211327886.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Z5NTEy,size_16,color_FFFFFF,t_70#pic_center)