<! [ CDATA [ ] ] >
在xml中,cdata是char nbsp;data的简写.
CDATA是不通过解析器进行解析的文本,文本中的标签不被看作标记。
一个简单的xml获取
@Test
public void test1() throws Exception {
SAXReader s=new SAXReader();
//在junit测试中 相对路径是从模块名开始的
Document read = s.read("xml/t.xml");
// System.out.println(read);
//通过Document对象获取根元素
Element rootElement = read.getRootElement();
//获取book标签对象
List<Element> books = rootElement.elements("book");
for(Element book:books){
//把标签对象转化为标签字符串
System.out.println(book.asXML());
}
for(Element book:books){
Element name = book.element("name");
System.out.println(name.asXML());
//获取标签内容
String text = name.getText();
System.out.println(text);
//直接获取标签内容,(上面方法分了两部)
String name1 = book.elementText("name");
String athor = book.elementText("athor");
String price = book.elementText("price");
System.out.println("------------");
System.out.println(name1);
//获取属性值
String sn = book.attributeValue("sn");
Book book1 = new Book(sn, name1, athor, Integer.parseInt(price));
System.out.println(book1);
}
}
<books>
<book sn="1">
<name>时间简史</name>
<athor>霍金</athor>
<price>10</price>
</book>
<book sn="2">
<name>白夜行</name>
<athor>东野圭吾</athor>
<!-- <price><<<<<<<<<<<<<20</price>-->
<!-- <price>-->
<!-- <![CDATA[-->
<!-- <<<<<<<<<<<<<20-->
<!-- ]]>-->
<!-- </price>-->
<price>20</price>
</book>
</books>