如何在java中获取具有两个属性的xml元素的文本
我想在一个有两个属性的元素中获取文本,示例xml如下所示如何在java中获取具有两个属性的xml元素的文本,java,xml,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">
<?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>
从测试中选择*;
从lop='a'所在的住宅中选择uftl、lop
输入:两个属性,输出:查询。i、 e,当输入为“master”时,“default”我希望得到该元素的查询,在本例中是“SELECT*fromtest”;“哦,我在等待你的回答时编写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;
}
}
}
下面是如何使用JDK/JRE中的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;
您想要使用什么xml解析器?请稍等几分钟,我尝试编写saxI使用JRE 1.6,不允许使用字符串的开关大小写。感谢您的回答。我可以通过少量修改获得DOM答案。SAX不工作。请更新为如何使用它?SAX有什么问题吗?@AlekseiBulgak-FYI,这里是如何使用它的im使用
javax.xml.xpath
API实现:以上哪种方法具有良好的性能?我的项目没有那么复杂,假设xml中的条目数不会超过50条。@user1787599-您需要分析以找到提供最佳性能的方法。在可读性和可维护性方面在代码中,javax.xml.xpath
方法显然是赢家。请注意,DOM/SAX方法依赖于文档中从来没有一个名为querys
或query
的元素,xpath方法确保您总是得到想要的东西。
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.
}
}
SELECT * from test;
SELECT uftl, lop from dwells where lop='a'
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;