gpt4 book ai didi

java - 阅读下面的 xml 的简单且最佳的方法是什么?

转载 作者:行者123 更新时间:2023-12-02 00:16:51 25 4
gpt4 key购买 nike

我是 XML 新手。

请让我知道在 java 中读取下面的 xml 的简单且最佳的方法。在我的 xml 中,我将查询作为根元素并将查询作为子元素。

<queries>
<query id="getUserByName">
select * from users where name=?
</query>
<query id="getUserByEmail">
select * from users where email=?
</query>
</queries>

我将传递查询ID,基于此我们需要获取相应的查询。请帮助我编写代码以便更好地理解。

最佳答案

使用 XPath,这很简单。

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

public class Test {

public static final String xml =
"<queries>"
+ " <query id=\"getUserByName\">"
+ " select * from users where name=?"
+ " </query>"
+ " <query id=\"getUserByEmail\">"
+ " select * from users where email=?"
+ " </query>"
+ "</queries>";


public static void main(String[] args) throws Exception {
System.out.println(getQuery("getUserByName"));
System.out.println(getQuery("getUserByEmail"));

}

public static String getQuery (String id) throws Exception {
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF8"));
InputSource inputSource = new InputSource(is);
XPath xpath = XPathFactory.newInstance().newXPath();
return xpath.evaluate("/queries/query[@id='" + id +"']", inputSource);
}
}

关于java - 阅读下面的 xml 的简单且最佳的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11766011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com