ava利用JDom來(lái)解析處理XML數(shù)據(jù)格式:
需要的包jdom-1.1.2.jar
1、將數(shù)據(jù)轉(zhuǎn)換成XML格式的數(shù)據(jù)進(jìn)行傳遞
Element rootList, firstList, secondItem, thirdItem; //根元素標(biāo)簽名 rootList = new Element("root"); //根元素標(biāo)簽內(nèi)的屬性名與值 rootList.setAttribute("project", pname); //生成Doc文檔 Document Doc = new Document(rootList); //獲取文檔中的根標(biāo)簽 rootList = Doc.getRootElement(); for (int i = 0; i < judges.size(); i++) { //生成新的元素 firstList = new Element("flayout"); firstList.setAttribute("percent", "percent"); //加入根級(jí)元素中 rootList.addContent(firstList); } XMLOutputter XMLOut = new XMLOutputter(); //將doc文檔轉(zhuǎn)換為字符串型的XML格式 String xmlinfo = XMLOut.outputString(Doc); //將開(kāi)頭的去掉 xmlinfo = xmlinfo.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""); //返回已經(jīng)封裝好的XML數(shù)據(jù) return xmlinfo; |
2、將字符串中的XML解析出進(jìn)行處理
//創(chuàng)建一個(gè)新的字符串 StringReader read = new StringReader(stadXML); // 創(chuàng)建新的輸入源SAX 解析器將使用 InputSource 對(duì)象來(lái)確定如何讀取 XML 輸入 InputSource source = new InputSource(read); // 創(chuàng)建一個(gè)新的SAXBuilder SAXBuilder sb = new SAXBuilder(); String projectName; List<Judgestandard> standIndex = new ArrayList<Judgestandard>(); try { // 通過(guò)輸入源構(gòu)造一個(gè)Document Document doc = sb.build(source); // 取的根元素 Element root = doc.getRootElement(); projectName = root.getAttributeValue("project"); // 得到根元素所有子元素的集合 Element et = null; List nodes = root.getChildren(); // 第一級(jí)指標(biāo) for (int i = 0; i < nodes.size(); i++) { et = (Element) nodes.get(i);// 循環(huán)依次得到子元素 Judgestandard judge = new Judgestandard(); //獲取該元素中屬性的值 String fid = et.getAttributeValue("mainid"); //獲取元素的孩子數(shù)目 List fsize = et.getChildren(); // 第二級(jí)指標(biāo) for (int j = 0; j < fsize.size(); j++) { et = (Element) fsize.get(j);// 循環(huán)依次得到子元素 et.getAttributeValue("stdid") } |
Java處理XML文檔
不需要包
待處理的XML文檔:
<?xml version="1.0" encoding="ISO-8859-1"?> <root> <ip>localhost</ip> <port>8080</port> </root> static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); static DocumentBuilder builder = null; builder = factory .newDocumentBuilder(); //獲取服務(wù)器根目錄地址 Document document = builder.parse(new File("src/ip.xml")); Element rootElement = document.getDocumentElement(); NodeList list1 = rootElement.getElementsByTagName("ip"); NodeList list2 = rootElement.getElementsByTagName("port"); Element ip = (Element) list1.item(0); Element port = (Element) list2.item(0); String s =ip.getFirstChild().getNodeValue().toString()+":"+port.getFirstChild().getNodeValue().toString(); System.out.println(s); |