【问题标题】:Retrieving XML data using a web service in Java使用 Java 中的 Web 服务检索 XML 数据
【发布时间】: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;

    }    
}

客户GUI sample of the program

【问题讨论】:

  • 你尝试了什么?哪个部分现在不工作?请给我们一些代码。
  • 您可以使用 DOM 解析器从 XML 文件中提取信息,然后检查传入 Web 服务的值。例如,查看这篇关于如何做到这一点的帖子:stackoverflow.com/questions/5059224/…。或者,您可以使用 SAX 解析器。但是,更根本的是,为什么不将翻译矩阵存储在关系数据库中呢?为什么它需要是 XML ?解析 XML 并将其作为 WS 调用的一部分进行搜索对我来说效率低下。
  • 这些是任务的要求。如何最好地检查为给定 xml 文件传递​​的值?

标签: java xml web-services xpath


【解决方案1】:

您可以以此为起点并根据需要进行修改。这意味着您需要使用 InputSource 对象加载文件,然后使用 XPath 从 XML 文件中提取数据。网上有很多关于如何做到这一点的示例和教程。下面的 sn-p 来自Simplest way to query XML in Java。

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(
xml));
String status = xpath.evaluate("/resp/status", source);

System.out.println("satus=" + status);

【讨论】:

  • 所以您的建议是在这种情况下使用 XPath 会比使用 DOM 更好。我会试试这个,很快就会回复。
  • 我并不是说它比 DOM 更好,但它是一种非常简单的方式来做你所描述的事情。 DOM 的问题在于,每次调用代码时,它都会读取并解析整个 XML 文件,而 SAX 会逐行解析文件,并且需要的内存要少得多。不确定 XPath 代码在内存使用中的表现如何,但您应该检查这是否是一个考虑因素。这个编程作业还有其他要求吗?
  • 要求是这样的:您需要创建两种不同语言之间的翻译服务。在服务中,单词的 DB 应放置在具有随机结构的 XML 文件中。当客户端请求翻译单个单词时,服务会验证 XML 文件中是否存在该单词并返回已翻译单词的值。否则,服务将返回错误消息。客户端使用所描述的服务调用带有 3 个字符串参数的 translate 方法,如前所述。
  • 我尝试创建一个使用 XPath 解析器并在服务中调用它的 XML 源类,但一直向我抛出 InvocationTargetException。我该如何解决这个其他问题?
【解决方案2】:
public class XMLSource {
    public String getTranslation(String original) throws Exception{
        Document doc;
         try {
            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);
            if ("".equals(translated)) return " word not found"; 

            return translated;
         } catch (Exception ex) {
             Logger.getLogger(XMLSource.class.getName()).log(Level.SEVERE, null, ex);
             return "Error";
         }
     }   

    private Document readData() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xmlFile = new File("translation.xml");/*enter the absolute path to the XML file.for example"C:\\Users\\User\\Documents\\NetBeansProjects\\WebServiceTranslate\\src\\java\\service\\translation.xml"*/ 
        return (Document) db.parse(new FileInputStream(xmlFile));
    }
}

【讨论】:

  • 你不应该从代码中返回像Error 这样的东西,因为这个值也可以是一个完全有效的转换为其他东西的值。在这种情况下,就让它崩溃吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多