【发布时间】:2016-09-19 09:37:51
【问题描述】:
我需要一些关于必须从 XML 文件中检索和检查有效元素的 Web 服务的帮助。 Web 服务方法应如下所示 - 翻译 ("flower","english","russian") 并且客户端应该能够允许您输入所需的单词、原始语言和目标语言。如果这些存在于 XML 文件中,它的翻译将显示在客户端,如果不存在,则会显示错误消息。
我创建了一个标准的 Web 服务方法 - add(int a, int b) 并使用普通的 java 应用程序创建了客户端部分,添加了一个 swing GUI,与 wsdl 链接连接,该方法运行良好。如何让这个程序发挥作用对我来说最好?请指教。
服务如下所示:
@WebMethod(operationName = "translate")
public String translate(@WebParam(name = "word") String word,
@WebParam(name = "originalLanguage") String originalLanguage,
@WebParam(name = "targetLanguage") String targetLanguage)
throws Exception {
XMLSource dataLSource = new XMLSource();
return dataLSource.getTranslation(word);
}
考虑到 XML 文件应如下所示:translation.xml
<?xml version="1.0" encoding="UTF-8"?>
<translation>
<word>
<english>car</english>
<russian>avtomobil</russian>
</word>
<word>
<english>flower</english>
<russian>tsvetok</russian>
</word>
<word>
<english>butterfly</english>
<russian>babochka</russian>
</word>
</translation>
还有 XML 源类:
public class XMLSource {
private Document readData() throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File xmlFile = new File("translation.xml");
return db.parse(new FileInputStream(xmlFile));
}
public String getTranslation(String original) throws Exception{
Document doc = readData();
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
XPathExpression xpe = xp.compile("/translation/word/russian[../english"
+ "/text()='"+original+"'] ");
String translated = (String) xpe.evaluate(doc, XPathConstants.STRING);
return translated;
}
}
【问题讨论】:
-
你尝试了什么?哪个部分现在不工作?请给我们一些代码。
-
您可以使用 DOM 解析器从 XML 文件中提取信息,然后检查传入 Web 服务的值。例如,查看这篇关于如何做到这一点的帖子:stackoverflow.com/questions/5059224/…。或者,您可以使用 SAX 解析器。但是,更根本的是,为什么不将翻译矩阵存储在关系数据库中呢?为什么它需要是 XML ?解析 XML 并将其作为 WS 调用的一部分进行搜索对我来说效率低下。
-
这些是任务的要求。如何最好地检查为给定 xml 文件传递的值?
标签: java xml web-services xpath