物联网实训笔记_java处理XML文档
生活随笔
收集整理的這篇文章主要介紹了
物联网实训笔记_java处理XML文档
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
DOMTest
讀API步驟,先看包,再看類,再讀類下面的方法,要注意方法需要的參數和返回值,邊用邊理解.
package com.qiuhu;/*import javax.lang.model.element.Element;*/ import javax.swing.text.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.Node;import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Element;public class DiskDom {public static void main(String[] args) throws Exception {//創建解析工廠DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();//創建解析器DocumentBuilder builder=factory.newDocumentBuilder();org.w3c.dom.Document document=builder.parse("src/com/qiuhu/disk.xml");NodeList nodes=document.getElementsByTagName("disk");org.w3c.dom.Node node=nodes.item(0);org.w3c.dom.Node n1=node.getFirstChild();org.w3c.dom.Node n2=n1.getNextSibling();org.w3c.dom.Node n3=node.getLastChild();NamedNodeMap attribut=node.getAttributes();org.w3c.dom.Node n4=attribut.item(0);/* String n=node.getFirstChild().getNodeValue();*/System.out.println( "disk"+n4.getNodeValue()+"size"+n1.getFirstChild()+"dirctory"+n2.getFirstChild()+"File"+n3.getFirstChild());}}先用XML文檔寫出相關文件
<?xml version="1.0" encoding="UTF-8"?> <disks><disk name="C盤"><size>10G</size><dirctory>10</dirctory><file>30</file></disk><disk name="D盤"><size>10G</size><dircetory>10</directory><file>20</file></disk> </disks>參照API,先得到解析工廠,在構造解析器,再使用相關方法讀取,代碼如下:
package com.qiuhu;import javax . xml. parsers. DocumentBuilder ; import javax . xml. parsers . DocumentBuilderFactory; import javax.xml.soap.Node;import org .w3c . dom. Document; import org. w3c. dom. Element; import org. w3c. dom. NodeList;public class DiskDom1 {public static void main(String[] args) throws Exception {//DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();//DocumentBuilder builder =factory.newDocumentBuilder();Document document=builder.parse("C:\\Users\\daier\\eclipse-workspace\\Project1\\src\\com\\qiuhu\\disk.xml");NodeList n1 =document . getElementsByTagName("disk");for(int i=0;i<n1. getLength();i++) {Element e=(Element)n1. item(i);System. out. print( "磁盤: "+e. getAttribute("name")+" ");System.out.print( "大小:"+e.getElementsByTagName("size"). item(0).getFirstChild().getNodeValue());System.out.print("文件:"+e.getElementsByTagName("directory").item(0). getFirstChild().getNodeValue());System.out.print( "目錄:"+e.getElementsByTagName ("file").item(0).getFirstChild().getNodeValue());}}}DOM實際讀取
上面方法是我們已經知道幾乎所有的節點是什么才進行的遍歷,實際上,在很大的文檔上幾乎不可能用上述方法遍歷.故而如下:
<?xml version="1.0" encoding="UTF-8"?><employees><employee id="1" depName="教學部"><name>rose</name><age>22</age><agender>female</agender><email>rose@briup.com</email><salary>8k</salary></employee> <employee id="2" depName="教學部"><name>jack</name><age>23</age><agender>male</agender><email>jack@briup.com</email><salary>9k</salary></employee> </employees>先構造Empoyee類,用來存放閱讀XML節點內容
package com.qiuhu;public class Employee { private int id; private String depName; private String name; private int age; private String gender; private String email; private String salary;public Employee() {super();// TODO Auto-generated constructor stub }public Employee(int id, String depName, String name, int age, String gender, String email, String salary) {super();this.id = id;this.depName = depName;this.name = name;this.age = age;this.gender = gender;this.email = email;this.salary = salary; }/*** @return the id*/ public int getId() {return id; }/*** @param id the id to set*/ public void setId(int id) {this.id = id; }/*** @return the depName*/ public String getDepName() {return depName; }/*** @param depName the depName to set*/ public void setDepName(String depName) {this.depName = depName; }/*** @return the name*/ public String getName() {return name; }/*** @param name the name to set*/ public void setName(String name) {this.name = name; }/*** @return the age*/ public int getAge() {return age; }/*** @param age the age to set*/ public void setAge(int age) {this.age = age; }/*** @return the gender*/ public String getGender() {return gender; }/*** @param gender the gender to set*/ public void setGender(String gender) {this.gender = gender; }/*** @return the email*/ public String getEmail() {return email; }/*** @param email the email to set*/ public void setEmail(String email) {this.email = email; }/*** @return the salary*/ public String getSalary() {return salary; }/*** @param salary the salary to set*/ public void setSalary(String salary) {this.salary = salary; }@Override public String toString() {return "Employee [id=" + id + ", depName=" + depName + ", name=" + name + ", age=" + age + ", gender=" + gender+ ", email=" + email + ", salary=" + salary + "]"; }}如舊解析工廠解析器,其后遍歷時將得到的元素節點的值賦予上一個類的相關值.即先確定節點的name,再確定其節點后續所有的文字信息value
package com.qiuhu;import java.util.List;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;import java.util.ArrayList;import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList;public class DomEmployee {//存放數據private static Employee employee;private static List<Employee> list=new ArrayList<Employee>();public static void main(String[] args) throws Exception {//構建解析工廠DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();//構建解析器DocumentBuilder builder =factory.newDocumentBuilder();//此處會拋出異常Document document=builder.parse("Project1/src/com/qiuhu/employee.xml");//直接讀取employee標簽,構建employeeduixiangNodeList n1=document.getElementsByTagName("employee");for(int i=1;i<n1.getLength();i++) {//遍歷一個employee標簽,構建一個employee對象Employee employee=new Employee();//將node轉換成element節點Element element=(Element) n1.item(i);int id=Integer.parseInt(element.getAttribute("id"));//API定義好的方法String depName=element.getAttribute("depName");System.out.println("id"+id+"depName"+depName);employee.setDepName(depName);employee.setId(id);//獲取employee節點的所有子節點,name age gender元素節點 不要換行之類的文本節點NodeList n12=element.getChildNodes();for (int j = 0; j < n12.getLength(); j++) {if(n12.item(j).getNodeType()==1) {String name=n12.item(j).getNodeName();String value=n12.item(j).getTextContent();if ("name".equals(name)) {employee.setName(value);}else if("gender".equals(name)){employee.setGender(value);}else if("name".equals(name)){employee.setAge(Integer.parseInt(value));}}}list.add(employee);}System.out.println("保存的用戶數"+list.size());}}SAX處理
package com.qiuhu;import javax.crypto.spec.DHGenParameterSpec; import javax.swing.text.html.HTMLEditorKit.Parser; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;public class DiskSAx {public static void main(String[] args) throws Exception {//創建SAX的解析工廠SAXParserFactory factory=SAXParserFactory.newInstance();//創建SAX的解析器SAXParser parser=factory.newSAXParser();//相對路徑不以"/"開頭//第一個參數為解析的文件,第二個參數才是需要解析的parser.parse("src/com/qiuhu/NewFile.xml",new MyHandler());}} class MyHandler extends DefaultHandler{@Overridepublic void startElement(String uri, String localName, String qName, Attributes attributes)throws SAXException {/*** 前兩個參數提供網絡應用,暫時不需要考慮* qName:表示標簽名* attribute:表示標簽屬性*/System.out.print("<"+qName);//輸出屬性內容for (int i = 0; i < attributes.getLength(); i++) {String attName=attributes.getQName(i);String attValue=attributes.getValue(attName);System.out.println(" "+attName+"='"+attValue+"'");}System.out.println(">");}@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {//charracter方法輸出文本 換行 空格String str=new String(ch,start,length);System.out.print(str);}@Overridepublic void endElement(String uri, String localName, String qName) throws SAXException {System.out.println("</"+qName+">");}}總結
以上是生活随笔為你收集整理的物联网实训笔记_java处理XML文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3-网页爬取-批量爬取贴吧页
- 下一篇: GMap.NET控件使用