在解析之前测试文档是否格式正确 [英] Test if document is well formed before parsing

查看:18
本文介绍了在解析之前测试文档是否格式正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要分析几千个 XML 文档,以查看其中的一些是否包含某种结构.问题是某些文档不包含格式良好的 XML.

I need to analyze a few thousand XML documents to see if some of them contains a certain construct. The problem is that some of the documents doesn't contain well formed XML.

基本思想是使用 fn:collection() 并在返回的节点内搜索.但这只有在集合中的所有文档都格式良好时才有效.

The basic idea was to use fn:collection() and search inside nodes returned. But this only works if all documents in the collection are well formed.

是否可以做类似的事情但只解析格式良好的文档?

Is it possible to do something similar but only parsing the well formed documents?

这是我的 XSLT,经过简化,如果 $dir 中的所有文档格式正确,它就可以工作:

This is my XSLT, simplified, which works if all documents in $dir are well formed:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:output method="text"/>
  <xsl:variable name="dir" as="xs:string">file:/c:/path/to/files/</xsl:variable>
  <xsl:variable name="files" select="concat($dir, '?select=*.xml')" as="xs:string"/>

  <xsl:template match="/">
    <xsl:variable name="docs" select="collection($files)"/>
    <xsl:variable name="names" select="
      for $i in $docs return
        distinct-values($i//*[exists(@an-attribute-to-find)]/local-name())"/>
    <xsl:value-of select="distinct-values($names)" separator="&#x0a;"/>
  </xsl:template>

</xsl:stylesheet>

在转换开始之前,是否可以在不手动整理格式不正确的文档的情况下执行此类操作?也许您对解决方案有更好的建议?

Would it be possible to do something like this without manually sorting out the non well formed documents before transformation starts? Maybe you have a better suggestion to a solution?

推荐答案

目前最好使用 XSLT 来完成.

At present this is best done out of XSLT.

如果您将要处理的所有文件名的列表作为外部参数 (<xsl:param>) 提供给转换,则可以在 XSLT 中完成——然后转换将使用标准 XPath 2.0 函数 doc-available() 并且只对这个函数返回的文档节点进行操作.

It can be done in XSLT if you provide as an exrternal parameter (<xsl:param>) to the transformation a list of all filenames to be processed -- then the transformation would use the standard XPath 2.0 function doc-available() and operate only on the document nodes returned by this function.

这篇关于在解析之前测试文档是否格式正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆