java - 当 XSD 的一部分嵌套在 WSDL 中时如何将架构添加到 Marshaller

标签 java jaxb wsdl marshalling xsd-validation

我想使用 XSD 来验证对 WebService 的请求。 问题是 XSD 的一部分嵌套在 WSDL 中,其余部分引用外部 XSD。 我想始终使用在线的。

我唯一的想法是从 WSDL 中提取整个 XSD 元素,并使用 DocumentBuilder 手动从这两个部分创建一个新的临时 XSD?

已经尝试过相同(负面)结果: Validating XML against multiple schemas extracted from WSDL

这个问题有现成的解决方案吗?

最佳答案

最终得到这个解决方案...大多数内容都是从其他解决方案复制粘贴的,抱歉我没有时间添加源。

    pathToWSDL = Is the path to the WSDL
    pathToWSDLRootPath root path of the WSDL, I need to add those to the imports because the schemaLocation where no relative paths in my case

    ...

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document wsdlDoc = db.newDocument();

    URL oracle = new URL(pathToWSDL);
    BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
    Source source = new StreamSource(in);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, new DOMResult(wsdlDoc));

    NodeList schemaNodes = wsdlDoc.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");

    int nrSchemas = schemaNodes.getLength();

    Source[] schemas = new Source[nrSchemas];

    for (int i = 0; i < nrSchemas; i++) {
        DOMSource domSource = new DOMSource(schemaNodes.item(i));

        //Update Schema location by adding path
        NodeList noteList = domSource.getNode().getChildNodes();
        for (int j = 0; j < noteList.getLength(); j++) {
            if("xsd:import".equals(noteList.item(j).getNodeName())){
                NamedNodeMap nodeMap = noteList.item(j).getAttributes();
                for (int attIndex = 0; attIndex < nodeMap.getLength(); attIndex++) {
                    if("schemaLocation".equals(nodeMap.item(attIndex).getNodeName())){
                        nodeMap.item(attIndex).setNodeValue(pathToWSDLRootPath + nodeMap.item(attIndex).getNodeValue());
                    }
                }
            }
        }
        //Show dump
        //StreamResult result = new StreamResult(System.out);
        //transformer.transform(domSource, result); 
        schemas[i] = domSource; 
    }

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemas);
    return schema;

关于java - 当 XSD 的一部分嵌套在 WSDL 中时如何将架构添加到 Marshaller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794623/

相关文章:

java - 在 JFreeChart 中显示值和系列名称

Java递归和 super 素数

java - JAXB - 解码时意外的元素 uri

java - 使用大型 wsdl,我们可以修剪它吗?

Java 开关不工作

java - 在 while 循环中要求用户再次玩的位置(猜谜游戏)

java - 如何让 JAXB 选择枚举?

java - 为什么无法将 XML 字符串转换为 JAXB 元素?

python - 在 python 中部署多个 web 服务,即多个 wsdl 文件

web-services - wsimport 如何从 WSDL 为 http :binding GET/POST 创建 Web 服务客户端