如何在java中使用两个属性获取元素的文本

时间:2013-02-12 05:27:48

标签: java xml

我想把文本放在一个有两个属性的元素里面,样本xml如下所示

    <?xml version="1.0" encoding="UTF-8"?>
    <queries>
    <query pagename="master" param="default">
        SELECT * from test;
    </query>
    <query pagename="uftl" param="default">
        SELECT uftl, lop from dwells where lop='a'
    </query>
    </queries>

输入:两个属性,输出:查询。即,在输入为'master'时,'default'我想获得该元素的查询,在这种情况下'SELECT * from test;“

2 个答案:

答案 0 :(得分:1)

哦。我在等你的答案时写dom解析器

private String parse(Document document) {
    Element root = document.getDocumentElement();
    NodeList queries = root.getElementsByTagName("queries");
    int queriesLength = queries.getLength();
    for (int i = 0; i < queriesLength; i++) {
        Element currentQuery = (Element) queries.item(i);
        if (currentQuery.getNodeType() == Element.ELEMENT_NODE) {
            String pagename = currentQuery.getAttributes()
                    .getNamedItem("pagename").getTextContent();
            String param = currentCategory.getAttributes()
                    .getNamedItem("param").getTextContent();
            if(param.equals(paramValue) && pagename.equals(pagename)){
               String query =  currnetNode.item(0).getTextContent();
                return query;
            }
            return null;
        }
    }
}

SAX解析器:

public class parser implements ContentHandler {
    boolean check = false;
    ArrayList<String> queries = new ArrayList<>();

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        switch (localName) {
            case "query":
                String param = atts.getValue("param");
                String pagename = atts.getValue("pagename");
                check = true;
                break;
            default:
                return;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
            check = false;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String tagContent = new String(ch, start, length).trim();
        if(check){
            if(!tagContent.isEmpty()){
                queries.add(tagContent);
            }
        }
    }

我删除了sum overriden方法,因为它们是空的并且在这里是不必要的。你必须实施它们并留空

<强>更新

班主:

public class Main {
    public static void main(String[] args) throws IOException, SAXException {
        ArrayList<String> queries = new parser().getQueries("test.xml");
        for (String query : queries){
            System.out.println(query);
        }

    }
}

解析器类:

public class parser implements ContentHandler {
    boolean check = false;
    ArrayList<String> queries = new ArrayList<>();

    public ArrayList<String> getQueries(String fileName) throws SAXException, IOException {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(this);
        xmlReader.parse(fileName);
        return queries;
    }

    @Override
    public void setDocumentLocator(Locator locator) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void startDocument() throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void endDocument() throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
    switch (localName) {
        case "query":
            String param = atts.getValue("param");
            String pagename = atts.getValue("pagename");
            if(!param.isEmpty() && !pagename.isEmpty())
                check = true;
            break;
        default:
            return;
    }
}

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
            check = false;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String tagContent = new String(ch, start, length).trim();
        if(check){
            if(!tagContent.isEmpty()){
                queries.add(tagContent);
            }
        }
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void processingInstruction(String target, String data) throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void skippedEntity(String name) throws SAXException {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}

我也在项目的根目录中添加了名为test.xml

的xml文件

我的输出看起来像这样:

SELECT * from test;
SELECT uftl, lop from dwells where lop='a'

答案 1 :(得分:1)

以下是如何使用JDK / JRE中的javax.xml.xpath API实现此用例的示例。

import javax.xml.namespace.QName;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {

        // Your query can be expressed as the following XPath.  It contains to
        // variables $pagename and $param that we can use to inject different
        // values into.
        String expression = "/queries/query[@pagename=$pagename and @param=$param]";

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xPath = xpf.newXPath();

        // We will use an instance of `XPathVariableResolver` to put the real
        // values into our XPath expression
        xPath.setXPathVariableResolver(new XPathVariableResolver() {

            @Override
            public Object resolveVariable(QName variableName) {
                if("pagename".equals(variableName.getLocalPart())) {
                    return "master";
                } else if("param".equals(variableName.getLocalPart())) {
                    return "default";
                }
                return null;
            }

        });

        InputSource source = new InputSource("src/forum14825994/input.xml");

        // When we execute the XPath we can ask that the result be returned to
        // us as a String
        String result = (String) xPath.evaluate(expression, source, XPathConstants.STRING);
        System.out.println(result);
    }

}

<强>输出

SELECT * from test;