Better way to parse xml

前端 未结 9 2103
感动是毒
感动是毒 2021-02-06 05:05

I\'ve been parsing XML like this for years, and I have to admit when the number of different element becomes larger I find it a bit boring and exhausting to do, here is what I m

9条回答
  •  野性不改
    2021-02-06 05:38

        import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    
    public class JXML {
    private DocumentBuilder builder;
    private Document doc = null;
    private DocumentBuilderFactory factory ;
    private XPathExpression expr = null;
    private XPathFactory xFactory;
    private XPath xpath;
    private String xmlFile;
    public static ArrayList XMLVALUE ;  
    
    
    public JXML(String xmlFile){
        this.xmlFile = xmlFile;
    }
    
    
    private void xmlFileSettings(){     
        try {
            factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            xFactory = XPathFactory.newInstance();
            xpath = xFactory.newXPath();
            builder = factory.newDocumentBuilder();
            doc = builder.parse(xmlFile);
        }
        catch (Exception e){
            System.out.println(e);
        }       
    }
    
    
    
    public String[] selectQuery(String query){
        xmlFileSettings();
        ArrayList records = new ArrayList();
        try {
            expr = xpath.compile(query);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i=0; i

    }

提交回复
热议问题