【问题标题】:Xerces - Load schema from stringXerces - 从字符串加载模式
【发布时间】:2016-06-22 14:38:44
【问题描述】:

我想使用 Xerces 从字符串加载 XML 模式,但到目前为止,我只能从 URI 加载它:

final XMLSchemaLoader xsLoader = new XMLSchemaLoader();
final XSModel xsModel = xsLoader.loadURI(file.toURI().toString()); 

可用的加载方法:

XSLoader {
    public XSModel load(LSInput is) { }
    public XSModel loadInputList(LSInputList is) { }
    public XSModel loadURI(String uri) { }
    public XSModel loadURIList(StringList uriList) { }
}

有没有从字符串加载 XML 模式的选项?在我的上下文中,处理是在客户端完成的,所以不能使用 URI 方法。

谢谢。

【问题讨论】:

    标签: java xsd schema xerces


    【解决方案1】:

    根据@TimBiegeleisen 的回答,我构建了一个将字符串转换为 XSModel 的方法。

    private static XSModel getSchema(String schemaText) throws ClassNotFoundException,
        InstantiationException, IllegalAccessException, ClassCastException {
        final InputStream stream = new ByteArrayInputStream(schemaText.getBytes(StandardCharsets.UTF_8));
        final LSInput input = new DOMInputImpl();
        input.setByteStream(stream);
    
        final XMLSchemaLoader xsLoader = new XMLSchemaLoader();
        return xsLoader.load(input);
    }
    

    【讨论】:

      【解决方案2】:

      我对你的问题不是特别熟悉,但我从ProgramCreek 中找到了这个有用的代码 sn-p,它演示了如何从LSInput 对象(上面列出的第一种方法)中获取XSModel。也可以从输入流加载 XML 模式。我稍微修改了代码以达到这个目的:

      private LSInput getLSInput(InputStream is) throws InstantiationException,
          IllegalAccessException, ClassNotFoundException {
          final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
          final DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
      
          LSInput domInput = impl.createLSInput();
          domInput.setByteStream(is);
      
          return domInput;
      }
      

      用法:

      // obtain your file through some means
      File file;
      LSInput ls = null;
      
      try {
          InputStream is = new FileInputStream(file);
      
          // obtain an LSInput object
          LSInput ls = getLSInput(is);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (Exception e) {
          e.printStackTrace();
      }
      
      if (ls != null) {
          XMLSchemaLoader xsLoader = new XMLSchemaLoader();
          XSModel xsModel = xsLoader.load(ls);
      
          // now use your XSModel object here ...
      }
      

      【讨论】:

      • 根据您的回答,我设法构建了一种将字符串转换为 XSModel 的方法。我将其发布以供将来参考,但将您的答案投票为已接受。
      • 感谢您的支持。您在问题中提供的一种方法接受了LSInput 对象,因此诀窍是找到一种将File 转换为LSInput 的方法。
      • 使用 LSInput.setStringData 可以节省 OP 几行代码。
      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 2017-03-14
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 2011-01-11
      • 2011-09-11
      • 2023-03-28
      相关资源
      最近更新 更多