java学习笔记Day9:xml

1.XML

1.1定义

XML(EXtensible Markup Language):可扩展标记语言,首先是一种语言

特点:

  • XML与操作系统、编程语言的开发平台无关
  • 实现不同系统之间的数据交换

1.2作用

1.2.1数据交互
1.2.2配置应用
1.2.3AJAX的基石

1.3XML的元素

XML标签:XML文档内容由一系列标签元素组成

1.3.1<元素名 属性名=“属性值”>元素内容</元素名>
  • 属性值用双引号包裹
  • 一个元素可以有多个属性
  • 属性值中不能直接包含<、“、&(不建议:‘、>),需要使用转义字符
1.3.2正常情况下,有元素内容,那么元素除了开始,还要有闭合
1.3.3但是,如果没有元素内容的情况下,可以写为自闭合标签形式<元素名 属性=’属性值’/>
1.3.4所有XML元素都必须有结束标签
1.3.5XML标签对大小写敏感
1.3.6XML必须正确的嵌套
1.3.7同级标签以缩进对齐
1.3.8元素名称可以包含字母、数字或其他的字符
1.3.9元素名称不能以数字或者标点符号开始
1.3.10元素名称中不能含空格
1.3.11<![CDATA[]]>:只能用于文本
1.3.12在编辑XML的时候,完全可以遵循面向对象的基本思路

1.4XML的基本结构

1.4.1节点:在XML当中,所有的内容,都是节点
1.4.2文档节点:

① 就是XML文件本身,就是文档节点

② 名称:Document

③ 类型:9

④ 值:无

1.4.3元素节点:

① 就是标签

② 名称:Element

③ 类型:1

④ 值:无

1.4.4属性节点:

① 属性定义在[标签/元素]当中

② 名称:Attribute

③ 类型:2

④ 值:有值

1.4.5文本节点:

① 在元素当中

② 名称:

③ 类型:

④ 值:

1.4.6注释节点
1.4.7实例

Q:将如下衣服的尺码信息,使用XML文件保存

衣服型号对应身高
S身高<165
M165<身高<170
L170<身高<175
XL175<身高<180
XXL180<身高<185
<?xml version="1.0" encoding="UTF-8"?>
<!-- 根节点 -->
<clothesList>
<!-- 这样写没问题,但是,不便解析
<clothes id="1" type="S" height="&lt;165">
</clothes>
<clothes id="1" type="S" maxHeight="165" minHeight="">
</clothes>
<clothes id="1" type="S">
<height maxHeight="165" minHeight=""/>
</clothes>
<clothes id="1" type="S">
<height name="max" value="165"/>
<height name="min" value=""/>
</clothes>
-->
<clothes id="1" type="S">
    <height name="max" value="165"/>
    <height name="min" value=""/>
    <explain>
        <![CDATA[随便写点什么1]]>
    </explain>
</clothes>
<clothes id="2" type="M">
    <height name="max" value="170"/>
    <height name="min" value="165"/>
    <explain>
        <![CDATA[随便写点什么2]]>
    </explain>
</clothes>
<clothes id="3" type="L">
    <height name="max" value="175"/>
    <height name="min" value="170"/>
    <explain>
        <![CDATA[随便写点什么3]]>
    </explain>
</clothes>
 <clothes id="1" type="XL">
    <height name="max" value="180"/>
    <height name="min" value="175"/>
    <explain>
        <![CDATA[随便写点什么1]]>
    </explain>
</clothes>
</clothesList> 
public static void main(String[] args) {
		//获取文件路径
		String path1 = Test.class.getResource("").getPath();//获取当前编译后的Test.class文件的绝对路径
		//D:/workspace1/class17/bin/com/m/demo1/
		System.out.println(path1);
		String path2 = Test.class.getResource("/").getPath();//获取当前编译后的Test.class所在bin目录的绝对路径
		//D:/workspace1/class17/bin
		System.out.println(path2);
		String path3 = Test.class.getResource("/demo1.xml").getPath();//直接获取bin目录下指定文件
		//D:/workspace1/class17/bin/demo1.xml
		System.out.println(path3);	
		//如果文件不存在
//		String path1 = Test.class.getResource("/demo2.xml").getPath();//如果文件不存在则返回Null值
//		System.out.println(path1);
//		String path5 = Test.class.getResource("demo2.xml").getPath();
//		System.out.println(path5);
		String path6 = new File(Test.class.getResource("").getPath()).getParent();
		System.out.println(path6);
		//直接获取工程根目录
		String path7 = Test.class.getClassLoader().getResource("").getPath();
		System.out.println(path7);
	}

1.5DOM解析XML

1.5.1DOM介绍
  • 文档对象模型(Document Object Model)
  • DOM把XML文档映射成一个倒挂的树
  • SAXReader:解析器
  • Document:定义XML文档
  • Element:定义XML元素
  • Text:定义XML文本节点
  • Attribute:定义了XML 的属性
1.5.2非web工程本地文件地址获取
序号举例
第一种Test.class.getResource("/文件名").getPath()
第二种Test.class.getClassLoader().getResource(“文件名”).getPath()
第三种new File("").getCanonicalPath()
第四种System.getProperty(“user.dir”)
第五种System.getProperty(“java.class.path”)
1.5.3DOM1J解析XML
  • 显示书籍收藏信息
  • 保存书籍收藏信息
  • 为书籍收藏信息添加新的节点
  • 修改/删除书籍收藏信息节点
1.5.4XML添加/解析
1.5.4.1解析xml
功能说明
sax.read(new FileInputStream(new File(f)))读取文件
document.getRootElement()获取跟节点
element.element(name)获取指定元素
element.elements([name])批量获取(指定)元素
element.attribute()获取属性
element.attributes([name])批量获取(指定)属性
element.getTextTrim()获取文本
element.getNodeType()获取节点类型
public static void main(String[] args) {
    String path = Test1.class.getClassLoader().getResource("demo1.xml").getPath();
//		System.out.println(path);//获取文件路径
    //读XML
    //获取SAXReader解析器
    SAXReader sax = new SAXReader();
    //读取文件
    try {
        Document document = sax.read(new File(path));
//			System.out.println(document.getNodeTypeName());
//			System.out.println(document.getNodeType());
        Element root = document.getRootElement();
//			System.out.println(root.getNodeTypeName());
//			System.out.println(root.getNodeType());
//			Element clo1 = root.element("clothes");//获取指定名称的元素,如果有重名,则获取第一个
//			List<Element> clos = root.elements();//获取所有的子元素,不包括孙子,只是儿子
        List<Element> clos = root.elements("clothes");//获取所有指定名称的子元素


        for(Element clo : clos){

//				Attribute idAtt = clo.attribute("id");
//				System.out.println(idAtt.getNodeTypeName());
//				System.out.println(idAtt.getNodeType());
//				System.out.println(idAtt.getStringValue());
//				Attribute typeAtt = clo.attribute("type");
            String id = clo.attributeValue("id");
            String type = clo.attributeValue("type");
            System.out.println("id:"+id + ",type:"+type);
​			List<Element> hs = clo.elements("height");for(Element h : hs){
​							    		      	System.out.println("name:"+h.attributeValue("name")+",value:"+h.attributeValue("value"));}
​			Element exp = clo.element("explain");
​			System.out.println(exp.getText());
​			System.out.println(exp.getTextTrim());
​			System.out.println(clo.elementTextTrim("explain"));;}} catch (DocumentException e) {
​		e.printStackTrace();}
}
1.5.4.2编辑XML
功能说明
DocumentHelper.createDocument()创建文档
DocumentHelper.createElement()创建元素
document.addDocType(doc1,doc2,doc3)设置文档DocType
ele.addElement(……)添加元素
ele.addComment(……)添加注释
ele.addAttribute(……)添加属性
ele.addText(……)添加文本
ele.addCDATA(……)添加cdata
OutputFormat format = OutputFormat.createPrettyPrint()format.setEncoding(“UTF-8”)格式化
XMLWriter writer = new XMLWriter(输出流, 格式化)writer.write(document)输出文档
public static void main(String[] args) throws Exception {
		//覆盖
		String path = Test2.class.getClassLoader().getResource("").getPath();
		File f = new File(path,"demo2.xml");
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Document document = DocumentHelper.createDocument();
		Element e = DocumentHelper.createElement("ele");//根节点
		document.add(e);
        Element e1 = DocumentHelper.createElement("ele1");
        e.add(e1);
        Attribute att1 = DocumentHelper.createAttribute(e1, "id", "1");
        e1.add(att1);
        e1.addCDATA("test1");	
        Element e2 = DocumentHelper.createElement("ele2");
    ​	e.add(e2);
    ​	Attribute att2 = DocumentHelper.createAttribute(e2, "id", "2");
    ​	e2.add(att2);
    ​	e2.addCDATA("test2");

    ​	OutputFormat format = OutputFormat.createPrettyPrint();	
    ​	format.setEncoding("UTF-8");

    ​	XMLWriter writer = new XMLWriter(new FileOutputStream(f), format);
    ​	writer.write(document);
    ​	writer.close();
}
		
public static void main(String[] args) throws Exception {
    //改--->先读再改
    String path = Test3.class.getClassLoader().getResource("demo2.xml").getPath();
    File f = new File(path);
    SAXReader r = new SAXReader();
    Document d = r.read(f);
    Element root = d.getRootElement();

    List<Element> eles = root.elements();

    Element e3 = DocumentHelper.createElement("ele3");
    Attribute att1 = DocumentHelper.createAttribute(e3, "id", "3");
    e3.add(att1);
    e3.addCDATA("test3");

    eles.add(e3);//添加到原本的集合当中去

    OutputFormat format = OutputFormat.createPrettyPrint();	
    format.setEncoding("UTF-8");

    XMLWriter writer = new XMLWriter(new FileOutputStream(f), format);
    writer.write(d);
    writer.close();

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值