Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Main {

    public static String getNodeAttributeFromXmlStr(String xmlStr, String nodeWeiZhi, String attributeName) {
        String result = "";
        try {
            xmlStr = xmlStr.trim();
            Element element = getRootNodeFromXmlStr(xmlStr);
            result = getNodeAttribute(element, nodeWeiZhi, attributeName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.replaceFirst(",", "");
    }

    private static Element getRootNodeFromXmlStr(String xmlStr) {
        Element element = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream is = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
            Document document = db.parse(is);
            element = document.getDocumentElement();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return element;
    }

    private static String getNodeAttribute(Element element, String nodeWeiZhi, String attributeName) {
        String result = "";
        String[] nodeNames = nodeWeiZhi.split(">");
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            String nodeName = node.getNodeName();
            if (nodeName.equals(nodeNames[0])) {
                if (nodeNames.length == 1) {
                    result += "," + node.getAttributes().getNamedItem(attributeName).getNodeValue().trim();
                }
                String nodeWeiZhiTemp = nodeWeiZhi.replaceFirst(nodeNames[0], "").replaceFirst(">", "");
                NodeList childrenTempList = node.getChildNodes();
                if (childrenTempList.getLength() > 0 && !nodeWeiZhiTemp.equals("")) {
                    result += getNodeAttribute((Element) node, nodeWeiZhiTemp, attributeName);
                }
            }
        }
        return result;
    }
}