博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Day01

Posted on 2019-03-18 18:19  lyhcc  阅读(138)  评论(0编辑  收藏  举报

Day01

1、注解

JDK 1.5添加
//@Test 测试
@Deprecated 弃用,当前有更好的实现
@SuppressWarning(“deprecation”) 压制弃用警告
@Override 覆盖重写

2、XML简介

扩展标记语言(Extensible Markup Language )。它被设计的宗旨是传输数据(或或者说是描述数据),而非显示数据
XML标签没有被预定义,需自行定义标签
W3C发布的(目前版本2000年xml1.0)
XML被广泛认为是继java之后internet上激动人心的新技术

3、XML作用
  • 可以在客户端(Client)和服务端(Server)之间传输数据
    服务器 (Intel 志强)
  • 保存相关数据
  • 用来做配置文件 在Android中 界面布局文件 mainfest配置文件
4、编码

GBK GB2312 UTF-8

5、XML 基本语法

文档声明
  最简单的文档声明 文档声明必须写在第一行
 保存的时候 xml声明的编码 要跟文件保存嘚编码保持一致 如果不声明 默认使用utf-8
 standalone属性标明文档是否独立,即是否依赖其他文档

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>

元素
 标签必须闭合,嵌套时先开始后闭合,
 如果标签我无内容,自闭合
  跟标签必须有一个且只有一个
命名规范

  • 区分大小写
  • 不能以数字或‘_’开头
  • 不能以xml开头
  • 不能包含空格
  • 名称中间不能包含冒号

注意换行制表符都会保留 书写的时候,如果用了这些符号 会浪费流量
属性

  • 属性写在开始标签中
  • 属性的命名规则和元素命名规则一样
  • 属性一定使用引号包起来(单双都行)
  • 属性可以使用子标签的形式来表示

注释
 不能在第一行,不能嵌套,
CDATA区

  • 里面内容不会被解析,

特殊字符

t特殊字符 替代符号
& &amp;
< &lt;
> &gt
" &quot
` &apos

xml约束
 格式良好的xml:遵循xml语法规则
 有效的XML:遵循约束文档的XML
 格式良好的不一定有效 有效的一定格式良好

6、常用的约束技术
  • XML DTD
    fcbde688a116ed34e5fd76e0dea60583.png
    53f345ee92461df74e086e3b16e87ad5.png
    d67782d0cb6b89cd9cd972eea84965bc.png
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE 书架 [
	<!ELEMENT 书架 (书+)>
	<!ELEMENT 书 (书名,作者,售价)>
	<!ELEMENT 书名 (#PCDATA)>
	<!ELEMENT 作者 (#PCDATA)>
	<!ELEMENT 售价 (#PCDATA)>
	<!ATTLIST 书
		ISBN ID #REQUIRED
		COMMENT (a|b) #IMPLIED
		出版社 CDATA "传智播客"
		>
	<!ENTITY copyright "黑马训练营">
]>
<书架>
	<书 ISBN="a" COMMENT="b" 出版社="" >
		<书名>Java就业培训教程</书名>
		<作者>&copyright;</作者>
		<售价>39.00元</售价>
	</书>	
	<书  ISBN="b">
		<书名>JavaScript网页开发</书名>
		<作者>张孝祥</作者>
		<售价>28.00元</售价>
	</书> 
</书架>
  • XML Schema
    XMLSchema也是一种用于定义和描述XML文档结构与内容的模
    式语言,其出现是为了克服 DTD的局限性
    XMLSchema VS DTD
      【1】XMLSchema符合XML语法结构
      【2】DOM、SAX等XML APl很容易解析出XML Schema文档中的内容
      【3】XML Schema对名称空间支持得非常好
      【4】XML Schema比XML DTD支持更多的数据类型,并支持用户自定义新的数据
      【5】XMLSchema定义约東的能力非常强大,可以对XML实例文档作出组致的语意限制
      【6】XML Schema不能像DTD一样定义实体,比DTD更复杂,但Xml Schema 现在已是w3c组织标准,逐步取代DTD
    名称空间 namespace 对应一个约束文档
    如:<html:Table></html:Table>
      <life:Table></life:Table>
    Schema 约束快速入门
      【1】XML Schema问阿金本身就是xml文件,但它的扩展名异常为.xsd
      【2】一个XML Schema称为模式文档,遵循这个的我们称为实例文档
      【3】XML Schema必须有一个根节点,且为
      【4】需绑定到一个URI地址上
    (标签 属性 文本)
  • XDR
  • SOX
7、解析xml文档dom

①Dom解析

整个文档加载到内存中分配一个树形结构
dom tree
优点: 方便增删改
缺点: 解析文件过大内存溢出
daf6e4666eac45980c62e411879b52d3.png
编程思路 DocumentBuilderFactory→DocumentBuilder →Document→通过节点获得NodeList→具体Node
如果想修改 TransformerFactory→Transformer→ Transform(source,Result)

      @Test

      public void domParser() throws ParserConfigurationException, 
SAXException, IOException{

            

            //获取DocumentBuilderFactory

            DocumentBuilderFactory builderFactory = 
DocumentBuilderFactory.newInstance();

            //获取DocumentBuilder

            DocumentBuilder builder = 
builderFactory.newDocumentBuilder();

            //通过documentBuilder获取Document对象

             org.w3c.dom.Document document = builder.parse("book.xml");

            //通过元素的名字找到元素的集合

            NodeList nodeList = document.getElementsByTagName("售价");

            //找到第二个元素

            org.w3c.dom.Node item = nodeList.item(0);

            //读出节点的文本内容

            String content = item.getTextContent();

            System.out.println(content);

      }

      @Test

      public void domModify() throws ParserConfigurationException, 
SAXException, IOException, TransformerFactoryConfigurationError, 
TransformerException {

            DocumentBuilderFactory builderFactory = 
DocumentBuilderFactory.newInstance();

            DocumentBuilder documentBuilder = 
builderFactory.newDocumentBuilder();

            org.w3c.dom.Document document = 
documentBuilder.parse("book.xml");

            NodeList nList = document.getElementsByTagName("售价");

            org.w3c.dom.Node item = nList.item(1);

            item.setTextContent("99.0");

            

            Transformer transformer = 
TransformerFactory.newInstance().newTransformer();

            //new DOMSource(document)数据源

            //new StreamResult("book.xml")目的地

            transformer.transform(new DOMSource(document), new 
StreamResult("book.xml"));

      }

②Sax解析

public void saxParser() throws ParserConfigurationException, 
SAXException, IOException {

            //获取工厂

            SAXParserFactory saxParserFactory = 
SAXParserFactory.newInstance();

            SAXParser saxParser = saxParserFactory.newSAXParser();

            //获取xmlReader通过这个reader可以设置ContentHandler

            XMLReader xmlReader = saxParser.getXMLReader();

            //不去直接实现ContentHandler,而是继承它的实现类DefaultHandler

            xmlReader.setContentHandler(new MyHandler());

            

            xmlReader.parse("book.xml");

      }

      /**

       * <u>sax</u>转AraryList

       * @throws ParserConfigurationException

       * @throws SAXException

       * @throws IOException 

       */



      public void saxParser2() throws ParserConfigurationException, 
SAXException, IOException {

            SAXParserFactory saxParserFactory = 
SAXParserFactory.newInstance();

            SAXParser saxParser = saxParserFactory.newSAXParser();

            XMLReader xmlReader = saxParser.getXMLReader();

            

            xmlReader.setContentHandler(new DefaultHandler() {

                  boolean isPrice = false;

                  int cnt = 0;

                  @Override

                  public void startElement(String uri, String localName, 
String qName, Attributes attributes)

                              throws SAXException {

                        if("售价".equals(qName)) {

                              isPrice = true;

                              cnt++;

                        }

                  }



                  @Override

                  public void endElement(String uri, String localName, 
String qName) throws SAXException {

                        if("售价".equals(qName)) {

                              isPrice = false;

                        }

                  }



                  @Override

                  public void characters(char[] ch, int start, int 
length) throws SAXException {

                        if(isPrice&&cnt==1) {

                              System.out.println(new String(ch, start, 
length));

                        }

                  }

                  

            });

            xmlReader.parse("book.xml");

            

      }

      @Test

      public void saxParserList() throws ParserConfigurationException, 
SAXException, IOException {

            SAXParserFactory saxParserFactory = 
SAXParserFactory.newInstance();

            SAXParser saxParser = saxParserFactory.newSAXParser();

            XMLReader reader = saxParser.getXMLReader();

            reader.setContentHandler(new DefaultHandler() {



                  private ArrayList<Book> books = null;

                  private Book book = null;

                  String tag = "";

                  @Override

                  public void startElement(String uri, String localName, 
String qName, Attributes attributes)

                              throws SAXException {

                        switch (qName) {

                        case "书架":

                              books  = new ArrayList<>();

                              break;

                        case "书":

                              book  = new Book();

                              break;

                        case "书名":

                              tag = "书名";

                              break;

                        case "作者":

                              tag = "作者";

                              break;

                        

                        case "售价":

                              tag = "售价";

                              break;

                        default:

                              break;

                        }

                  }



                  @Override

                  public void endElement(String uri, String localName, 
String qName) throws SAXException {

                        tag = "";

                        if("书架".equals(qName)) {

                              for(Book book:books) {

                                    System.out.println(book);

                              }

                        }else if("书".equals(qName)){

                              books.add(book);

                        }

                  }



                  @Override

                  public void characters(char[] ch, int start, int 
length) throws SAXException {

                        String string = new String(ch, start, length);

                        switch (tag) {

                        case "书名":

                              book.setName(string);

                              break;

                        case "作者":

                              book.setAuthor(string);

                              break;

                        case "售价":

                              book.setPrice(string);

                              break;

                        default:

                              break;

                        }

                        

                  }

                  

            });

            reader.parse("book.xml");

      }

      

      private class MyHandler extends DefaultHandler{



            @Override

            public void startDocument() throws SAXException {

                  System.out.println("文档开始");

            }



            @Override

            public void endDocument() throws SAXException {

                  System.out.println("文档结束");

            }



            @Override

            public void startElement(String uri, String localName, 
String qName, Attributes attributes)

                        throws SAXException {

                  System.out.println("<" + qName+">");

            }



            @Override

            public void endElement(String uri, String localName, String 
qName) throws SAXException {

                  System.out.println("</"+qName+ ">");

            }



            @Override

            public void characters(char[] ch, int start, int length) 
throws SAXException {

                  String string = new String(ch, start, length);

                  System.out.println(string);

            }

            

            

      }


③Pull解析
与此相关的jar包

public void pullParser() throws XmlPullParserException, IOException {

            ArrayList<Book> list = null;

            Book book = null;

            //获取工厂

            XmlPullParserFactory factory = 
XmlPullParserFactory.newInstance();

            //获取<u>Xml</u>解析器

            XmlPullParser parser = factory.newPullParser();

            //给解析器设置输入源

            //第一个参数类型是输入流,第二个是文档用到的字符集

            parser.setInput(new FileInputStream(new File("book.xml")), 
"utf-8");

            

            //获取当前事件

            int eventType = parser.getEventType();

            while(eventType!=XmlPullParser.END_DOCUMENT) {

                  switch (eventType) {

                  case XmlPullParser.START_TAG:

                        //获取当前标签名 parser.getName()

                        if("书架".equals(parser.getName())) {

                              //创建一个集合

                              list = new ArrayList<>();

                        }else if ("书".equals(parser.getName())) {

                              //创建Book对象

                              book = new Book();

                              //parser.nextText() 获取当前的节点的下一个文本

                        }else if ("书名".equals(parser.getName())) {

                              //book对象设置name属性

                              book.setName(parser.nextText());

                        }else if ("作者".equals(parser.getName())) {

                              //book对象设置author属性

                              book.setAuthor(parser.nextText());

                        }else if ("售价".equals(parser.getName())) {

                              //book对象设置price属性

                              book.setPrice(parser.nextText());

                        }

                        

                        break;

                  case XmlPullParser.END_TAG:

                        

                        //巴蜀对象添加到list集合中

                        if("书".equals(parser.getName())) {

                              list.add(book);

                        }

                        break;

                  default:

                        break;

                  }

                  

                  //调用下一个事件

                  eventType = parser.next();

            }

            //遍历list集合

            for(Book e:list) {

                  System.out.println(e);

            }

      }


8、JSON(JavaScript Object Notation)

一种简单的数据格式,比xml更轻巧
规则简单
1)映射使用“:”表示。名称:值
2)并列数据之间使用逗号分隔。名称1:值1,名称2:值2
3)映射的集合用大括号表示。{名称1:值1,名称2:值2}
4)并列数据使用方括号“[]”.[{名称1:值1,名称2:值2},{名称1:值1,名称2:值2}]
元素值可具有的类型:string,number,object,array,true,false,null
常见API

//将json字符串转成JSONObject对象
JSONObject jb = new JSONObject(String source);
Object get(String key)
int getInt(String key)
String getString(String key)
XXX getXXX(String key)
JSONArray getJSONArray(String key)

//将字符串转换出JSONArray对象
JSONArray jsArray = new JSONArray(String source)

与JSON相关的jar包

      public void jsonTest() throws JSONException {

            String jString = "{'name':'张三','age':'20'}";

            //根据具有<u>json</u>格式的字符串就可以创建一个<u>json</u>对象

            JSONObject obj = new JSONObject(jString);

            //获取对象后 就可以通过key去取值 根据需求选择相关的getXXX方法

            //可以获取的类型 string long double boolean object

            String name = obj.getString("name");

            int age = obj.getInt("age");

            System.out.println(name + " , " + age);

      }