Java利用JDom解析和传递XML格式数据

    xiaoxiao2022-07-15  144

    j ava利用JDom来解析处理XML数据格式:

      需要的包jdom-1.1.2.jar

      1、将数据转换成XML格式的数据进行传递

    Element rootList, firstList, secondItem, thirdItem; //根元素标签名 rootList = new Element("root"); //根元素标签内的属性名与值 rootList.setAttribute("project", pname); //生成Doc文档 Document Doc = new Document(rootList); //获取文档中的根标签 rootList = Doc.getRootElement();   for (int i = 0; i < judges.size(); i++) {    //生成新的元素 firstList = new Element("flayout"); firstList.setAttribute("percent", "percent"); //加入根级元素中 rootList.addContent(firstList); } XMLOutputter XMLOut = new XMLOutputter(); //将doc文档转换为字符串型的XML格式 String xmlinfo = XMLOut.outputString(Doc); //将开头的去掉 xmlinfo = xmlinfo.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""); //返回已经封装好的XML数据 return xmlinfo;

      2、将字符串中的XML解析出进行处理

    //创建一个新的字符串 StringReader read = new StringReader(stadXML); // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); // 创建一个新的SAXBuilder SAXBuilder sb = new SAXBuilder(); String projectName; List<Judgestandard> standIndex = new ArrayList<Judgestandard>();   try {     // 通过输入源构造一个Document     Document doc = sb.build(source);     // 取的根元素     Element root = doc.getRootElement();     projectName = root.getAttributeValue("project");     // 得到根元素所有子元素的集合     Element et = null;     List nodes = root.getChildren();     // 第一级指标     for (int i = 0; i < nodes.size(); i++) {        et = (Element) nodes.get(i);// 循环依次得到子元素        Judgestandard judge = new Judgestandard(); //获取该元素中属性的值        String fid = et.getAttributeValue("mainid");         //获取元素的孩子数目        List fsize = et.getChildren();        // 第二级指标        for (int j = 0; j < fsize.size(); j++) {            et = (Element) fsize.get(j);// 循环依次得到子元素            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(); //获取服务器根目录地址 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);

    ====================================分割线================================

    最新内容请见作者的GitHub页:http://qaseven.github.io/

    相关资源:七夕情人节表白HTML源码(两款)
    最新回复(0)